Spring
[Spring] Spring 핵심 원리 : 의존관계 주입의 옵션 처리
yjk490
2023. 7. 14. 14:46

주입할 스프링 빈 없이 애플리케이션이 동작한다면 어떻게 될까? @Autowired의 required 옵션 기본값은 true이기 때문에 자동 주입 대상이 없으면 에러가 발생한다. 자동 의존관계 주입을 옵션 처리하는 방법은 다음과 같다.
- @Autowired(required=false) : 주입할 대상이 없으면 메서드 자체를 호출하지 않는다.
- @Nullable : 주입할 대상이 없으면 null로 처리한다. 즉, 아무것도 대입하지 않는다.
- Optional<> :주입할 대상이 없으면 Optional.empty가 저장된다.
ApplicationContext에 매개변수로 전달되는 설정 클래스 또한 스프링 빈으로 등록되기 때문에 TestBean 안에 @Autowired를 사용했다. 그리고 Member는 스프링 컨테이너에 빈으로 등록되지 않은 클래스다.
public class AutowiredOptionTest {
@Test
void autowiredOption() {
ApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class);
}
static class TestBean {
// 컨테이너에 등록되지 않은 빈(Member)을 주입
@Autowired(required = false)
public void setNoBean1(Member noBean1) {
System.out.println("noBean1 = " + noBean1);
}
@Autowired
public void setNoBean2(@Nullable Member noBean2) {
System.out.println("noBean2 = " + noBean2);
}
@Autowired
public void setNoBean3(Optional<Member> noBean3) {
System.out.println("noBean3 = " + noBean3);
}
}
}
/* 실행 결과
noBean2 = null
noBean3 = Optional.empty
*/
실행 결과를 보면 required 옵션을 사용한 메서드는 아예 호출되지 않았고, 언급했다시피 noBean2와 noBean3는 각각 null, Optional.empty가 출력되었다.