우리 언니 보구 싶다... 내 인생 첫번째 베프인데...
@Autowired
의 required
옵션의 기본값이 true @Autowired(required=false)
: 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출 안됨@Autowired(required = false)
public void setNoBean1(Member noBean1) { //Member <- 스프링 빈 X
System.out.println("noBean1 = " + noBean1);
}
➡️ 실행 결과 : 호출 되지 않는다.
org.springframework.lang.@Nullable
: 자동 주입할 대상이 없으면 null이 입력된다.@Autowired
public void setNoBean2(@Nullable Member noBean2) {
System.out.println("noBean2 = " + noBean2);
}
➡️ 실행 결과 : noBean2 = null
Optional<>
: 자동 주입할 대상이 없으면 Optional.empty
가 입력된다.@Autowired
public void setNoBean3(Optional<Member> noBean3) {
System.out.println("noBean3 = " + noBean3);
}
➡️ 실행 결과 : noBean3 = Optional.empty
전체 코드
public class AutowiredTest {
/*
@Autowired(required=false) : 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출 안됨
org.springframework.lang.@Nullable : 자동 주입할 대상이 없으면 null이 입력된다.
Optional<> : 자동 주입할 대상이 없으면 Optional.empty 가 입력된다.
*/
@Test
void autowiredOption() {
ApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class);
}
static class TestBean {
@Autowired(required = false)
public void setNoBean1(Member noBean1) { //Member <- 스프링 빈 X
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);
}
}
}
참고: @Nullable, Optional은 스프링 전반에 걸쳐서 지원된다. 예를 들어서 생성자 자동 주입에서 특정 필드에
만 사용해도 된다.
더 잘하구 싶다..?! 정말?!!