1. 의존성 주입을 각 클래스에서 선언하여 처리하기
- 지금까지 의존성 주입을 컨테이너에서 autowire 옵션을 통해 처리하였다
- component-scan 기능을 통해서 객체를 컨테이너에 로딩하면 이에 대한 의존성 주입을 컨테이너에서 처리한다는 것은 번거롭다.
- 처리 단계
1) component-scan를 통해서 컨테이너에 객체 생성
2) 해당 패키지에 클래스 생성시, component-scan에서 지정한 annotation 설정
3) 주입할 객체 생성시, @Autowired private 클래스명 참조명;
4) 위 annotation 옵션으로 new 생성자() 없이도, 컨테이너에 있는 객체가 해당 객체에 자동으로 주입된다.
@@ dispatcher-servlet.xml
// springweb 하위에 @Controller, @Service, @Repository 선언된 모든 클래스를 메모리에 로딩시킨다.
<context:component-scan base-package="springweb">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
@@ Controller.java
@Controller
public class A01_DIController {
// 컨테이너(dispatcher-servlet.xml) 안에 있는 A02_DIService 객체를 자동주입
@Autowired
private A02_DIService service;
// http://localhost:7080/springweb/diCall01.do
@GetMapping("/diCall01.do")
public String diCall01(Model d) {
System.out.println("## 의존성 주입??"+service.getCheck());
d.addAttribute("show",service.getCheck());
return "WEB-INF\\views\\a01_start\\a20_autowireShow.jsp";
}
@@ Service.java
@Service
public class A02_DIService {
public String getCheck() {
return "주입이 되었습니다";
}
}