스프링 IoC 컨테이너에서 DAO 빈 등록하기
이 글에서는 스프링 IoC 컨테이너에 DAO 빈을 등록할 것이다. 우리는 웹 개발을 하면서 다양한 데이터베이스에 접근한다. DAO는 이러한 데이터에 접근할 때 추상 인터페이스를 제공하는 객체이다. 이번 글에서는 간단한 DAO를 직접 만들고 스프링 IoC 컨테이너에 직접 등록해 볼 것이다.
먼저 DAO로 처리할 도메인 클래스를 만들어 보자. 도메인 클래스는 Student이다.
@Data
@AllArgsConstructor
public class Student {
private long id;
private String name;
}
그 다음으로는 DAO를 만들어보자. DAO 인터페이스는 id로 질의해서 Student 객체를 가져올 수 있다.
public interface StudentDao {
Student getStudentById(int id);
}
이어서 DAO 인터페이스를 구현한 객체를 만들고 스프링 IoC 컨테이너에 등록해보자. @Component를 사용하면 스프링 IoC 컨테이너가 컴포넌트 스켄을 통해 해당 클래스를 빈으로 등록한다. 그리고 DAO 객체가 생성되면서 테스트 하기위한 초기 데이터를 몇개 적재 하였다.
@Component("studentDao")
public class StudentDaoImpl implements StudentDao {
private final List<Student> students = new ArrayList<Student>();
public StudentDaoImpl() {
students.add(new Student(0, "Kim"));
students.add(new Student(1, "Lee"));
students.add(new Student(2, "Park"));
}
public Student getStudentById(int id) {
return students.get(id);
}
}
마지막으로, 스프링 IoC 컨테이너에서 DAO 객체를 사용하여 저장된 Student 객체를 불러와 보자.
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContex("com.firewood");
StudentDao studentDao = context.getBean(StudentDao.class);
System.out.println(studentDao.getStudentById(0).getName()); //Kim
System.out.println(studentDao.getStudentById(1).getName()); //Lee
System.out.println(studentDao.getStudentById(2).getName()); //Park
}
참고도서
제목: 스프링5레시피(4판)
지은이: 마틴데니엄, 다니엘 루비오, 조시 롱
펴낸곳: 한빛미디어