STS3 스프링 회원 정보 관리 예제

계리·2024년 2월 20일
0

이번에는 회원 정보를 관리하는 컴포넌트를 추가해서 공부해보려고 한다.

회원 정보에 대한 컴포넌트를 구성하는 각 자바 파일들의 위치이다.


UserVO.java

VO(또는 DTO) 클래스를 생성할 때는 해당 VO의 테이블 구조를 확인하고 만들면 된다. 지금처럼 UserVO를 만들려면 데이터베이스에서 User 테이블의 구조를 확인하면 된다. 어떠한 항목이 들어갔는지 확인하고 해당 테이블 항목에 맞춰서 VO 클래스의 멤버 변수들을 선언해주면 된다.

package com.springbook.biz.user;

//	VO(Value Object)
public class UserVO {
	private String id;
	private String password;
	private String name;
	private String role;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	
	@Override
	public String toString() {
		return "UserVO [id=" + id + ", password=" + password + ", name=" + name + ", role=" + role + "]";
	}
}

UserDAO.java

게시판 컴포넌트의 BoardDAO.java와 같이 JDBC를 이용하여 데이터베이스에 접근하고 데이터들을 CRUD를 할 수 있는 메서드들을 만들어 해당 객체들을 리턴해준다.

package com.springbook.biz.user.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.springbook.biz.common.JDBCUtil;
import com.springbook.biz.user.UserVO;

// DAO(Data Acess Object)
public class UserDAO {
	// JDBC 관련 변수
	private Connection conn = null;
	private PreparedStatement stmt = null;
	private ResultSet rs = null;
	
	//	SQL 명령어들
	private final String USER_GET = "select * from users where id=? and password=?";

	//	CRUD 기능의 메서드 구현
	//	회원 등록
	public UserVO getUser(UserVO vo) {
		UserVO user = null;
		try {
			System.out.println("===> JBCD로 getUser() 기능 처리");
			conn = JDBCUtil.getConnection();
			stmt = conn.prepareStatement(USER_GET);
			stmt.setString(1, vo.getId());
			stmt.setString(2, vo.getPassword());
			rs = stmt.executeQuery();
			if(rs.next()) {
				user = new UserVO();
				user.setId(rs.getString("ID"));
				user.setPassword(rs.getString("PASSWORD"));
				user.setName(rs.getString("NAME"));
				user.setRole(rs.getString("ROLE"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(rs, stmt, conn);
		}
		
		return user;
	}
}

UserService.java

구현체를 위해 인터페이스로 클래스를 생성하고 메서드는 빈 껍데기를 만든다.

package com.springbook.biz.user;

public interface UserService {

	//	CRUD 기능의 메서드 구현
	//	회원 등록
	public UserVO getUser(UserVO vo);
}

UserServiceoImpl.java

구현체를 작성하고 UserDAO 객체를 이용하여 DB연동을 처리하기 위해 멤버 변수로 UserDAO 선언하고 setter 메서드를 추가했다.

package com.springbook.biz.user.impl;


import com.springbook.biz.user.UserService;
import com.springbook.biz.user.UserVO;

public class UserServiceImpl implements UserService {
	private UserDAO userDAO;
	
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	public UserVO getUser(UserVO vo) {
		return userDAO.getUser(vo);
	}
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						https://www.springframework.org/schema/beans/spring-beans.xsd
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<context:component-scan base-package="com.springbook.biz" />
	
	<bean id="userService" class="com.springbook.biz.user.impl.UserServiceImpl">
		<property name="userDAO" ref="userDAO" />
	</bean>
	
	<bean id="userDAO" class="com.springbook.biz.user.impl.UserDAO" />
</beans>

UserServiceClient.java

테스트를 위해 UserServiceClient 클래스를 생성했다.

package com.springbook.biz.user;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;


public class UserServiceClient {

	public static void main(String[] args) {
		// 1. Spring 컨테이너를 구동한다.
		AbstractApplicationContext container =
				new GenericXmlApplicationContext("applicationContext.xml");
		
		// 2. Spring 컨테이너로부터 BoardServiceImp 객체를 Lookup한다.
		UserService userService = (UserService) container.getBean("userService");

		// 3. 로그인 기능 테스트
		UserVO vo = new UserVO();
		vo.setId("test");
		vo.setPassword("test123");
		
		UserVO user = userService.getUser(vo);

		if(user != null) {
			System.out.println(user.getName() + "님 환영합니다.");
		} else {
			System.out.println("로그인 실패");
		}
		
		// 4. Spring 컨테이너를 종료한다.
		container.close();
	}

}
실행 결과
DEBUG: org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [/Users/chokyeil/Desktop/DEV-STS/workspace-sts-3.9.18.RELEASE/BoardWeb/target/classes/com/springbook/biz/board/impl/BoardDAO.class]
DEBUG: org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [/Users/chokyeil/Desktop/DEV-STS/workspace-sts-3.9.18.RELEASE/BoardWeb/target/classes/com/springbook/biz/board/impl/BoardServiceImpl.class]
DEBUG: org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 9 bean definitions from class path resource [applicationContext.xml]
DEBUG: org.springframework.context.support.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@16aa8654
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'boardDAO'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'boardService'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'userService'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'userDAO'
===> JBCD로 getUser() 기능 처리
관리자님 환영합니다.
DEBUG: org.springframework.context.support.GenericXmlApplicationContext - Closing org.springframework.context.support.GenericXmlApplicationContext@16aa8654, started on Tue Feb 20 22:49:09 KST 2024

어노테이션 적용

컴포넌트들의 bean등록을 applicationContext.xml에 등록을 해서 컴포넌트를 사용했는데 xml에 등록하는 대신 어노테이션을 이용해 등록하는 방법이 있다.


applicationContext.xml

먼저 위에서 user에 관한 bean등록을 했던 소스를 주석 처리한다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						https://www.springframework.org/schema/beans/spring-beans.xsd
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<context:component-scan base-package="com.springbook.biz" />
	
<!-- 	<bean id="userService" class="com.springbook.biz.user.impl.UserServiceImpl">
		<property name="userDAO" ref="userDAO" />
	</bean>
	
	<bean id="userDAO" class="com.springbook.biz.user.impl.UserDAO" /> -->
</beans>

UserServiceoImpl.java

@Service, @Autowired 어노테이션을 추가한다.

package com.springbook.biz.user.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.springbook.biz.user.UserService;
import com.springbook.biz.user.UserVO;

@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDAO userDAO;
	
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	public UserVO getUser(UserVO vo) {
		return userDAO.getUser(vo);
	}
}

UserDAO.java

@Repository 어노테이션을 추가하고 다시 UserServiceClient.java를 실행하면 위에서 실행 결과와 같이 나온다.

package com.springbook.biz.user.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.springframework.stereotype.Repository;

import com.springbook.biz.common.JDBCUtil;
import com.springbook.biz.user.UserVO;

// DAO(Data Acess Object)
@Repository("userDAO")
public class UserDAO {
	// JDBC 관련 변수
	private Connection conn = null;
	private PreparedStatement stmt = null;
	private ResultSet rs = null;
	
	//	SQL 명령어들
	private final String USER_GET = "select * from users where id=? and password=?";

	//	CRUD 기능의 메서드 구현
	//	회원 등록
	public UserVO getUser(UserVO vo) {
		UserVO user = null;
		try {
			System.out.println("===> JBCD로 getUser() 기능 처리");
			conn = JDBCUtil.getConnection();
			stmt = conn.prepareStatement(USER_GET);
			stmt.setString(1, vo.getId());
			stmt.setString(2, vo.getPassword());
			rs = stmt.executeQuery();
			if(rs.next()) {
				user = new UserVO();
				user.setId(rs.getString("ID"));
				user.setPassword(rs.getString("PASSWORD"));
				user.setName(rs.getString("NAME"));
				user.setRole(rs.getString("ROLE"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(rs, stmt, conn);
		}
		
		return user;
	}
}

혹시라도 아래와 같이 오류가 나타나면 UserServiceoImpl.java 클래스에서 @Service옆에 bean 이름을 설정해줬는지 확인을 해보면 된다. 빈 이름을 설정해주지 않아 해당 컴포넌트를 차지 못하서 생기는 오류이다. 밑에 오류 내용에서 핵심은 Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userService' available 이다

DEBUG: org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [/Users/chokyeil/Desktop/DEV-STS/workspace-sts-3.9.18.RELEASE/BoardWeb/target/classes/com/springbook/biz/board/impl/BoardDAO.class]
DEBUG: org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [/Users/chokyeil/Desktop/DEV-STS/workspace-sts-3.9.18.RELEASE/BoardWeb/target/classes/com/springbook/biz/board/impl/BoardServiceImpl.class]
DEBUG: org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [/Users/chokyeil/Desktop/DEV-STS/workspace-sts-3.9.18.RELEASE/BoardWeb/target/classes/com/springbook/biz/user/impl/UserDAO.class]
DEBUG: org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [/Users/chokyeil/Desktop/DEV-STS/workspace-sts-3.9.18.RELEASE/BoardWeb/target/classes/com/springbook/biz/user/impl/UserServiceImpl.class]
DEBUG: org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 9 bean definitions from class path resource [applicationContext.xml]
DEBUG: org.springframework.context.support.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@16aa8654
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'boardDAO'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'boardService'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'userDAO'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'userServiceImpl'
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userService' available
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:863)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1344)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154)
	at com.springbook.biz.user.UserServiceClient.main(UserServiceClient.java:15)

참고

profile
gyery

0개의 댓글