// 1. 생성자주입(Constructor Injection)
@Component
public class MadExample {
// final로 선언할 수 있는 보너스
private final HelloService helloService;
// 단일 생성자인 경우는 추가적인 어노테이션이 필요 없다.
public MadExample(HelloService helloService) {
this.helloService = helloService;
}
}
// 2. 필드주입(Field Injection)
@Component
public class MadExample {
@Autowired
private HelloService helloService;
}
// 3. 수정자주입(Setter Injection)
@Component
public class MadExample {
private HelloService helloService;
@Autowired
public void setHelloService(HelloService helloService) {
this.helloService = helloService;
}
}
1. 순환참조를 방지할 수 있다
순환참조를 한 경우 다른방식은 애플리케이션이 아무 오류나 경고없이 구동이되서 문제가될 수 있지만, 생성자주입방식으로 실행시 BeanCurrentlyInCreationException이 발생하며 애플리케이션이 구동조차안된다. 생성자 주입 방법은 필드 주입이나 수정자 주입과는 빈을 주입하는 순서가 다르기 때문.
** 빈이란?
Spring IoC 컨테이너가 관리하는 자바 객체를 빈(Bean)이라는 용어로 부른다.
우리가 new 연산자로 어떤 객체를 생성했을 때 그 객체는 빈이 아니다.
ApplicationContext.getBean()으로 얻어질 수 있는 객체는 빈이다.
즉 Spring에서의 빈은 ApplicationContext가 알고있는 객체, 즉 ApplicationContext가 만들어서 그 안에 담고있는 객체를 의미한다.
즉 순환참조가 발생하는 경우 애플리케이션이 구동되지 않는다.
2. 테스트에 용이하다
3.가독성이 좋아진다
4.불변성