1. @Autowired(required=false) : 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출 안됨
2. org.springframework.lang.@Nullable : 자동 주입할 대상이 없으면 null이 입력된다.
3. Optional<> : 자동 주입할 대상이 없으면 Optional.empty 가 입력된다.
참고: @Nullable, Optional은 스프링 전반에 걸쳐서 지원된다. 예를 들어서 생성자 자동 주입에서 특정필드에만 사용해도 된다.
생성자에서 파라미터가 3개 있는데 마지막 것은 스프링 빈에 없는데 호출하고 싶다면 @Nullable로 할 수 있다!
AutoWiredTest.java
package hello.core.autowired;
import hello.core.member.Member;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.lang.Nullable;
import java.util.Optional;
public class AutoWiredTest {
@Test
void AutowiredOption(){
//ComponentScan처럼 TestBean을 빈 등록해준다!
ApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class);
}
static class TestBean {
//스프링에 빈이 없는 경우(스프링 컨테이너에 등록되지 않은 일반 클래스 Member)
//1. 메서드 자체가 호출되지 않는다!
@Autowired(required = false)//required의 기본값은 true.
public void setNoBean1(Member noBean1){
System.out.println("noBean1 = " + noBean1);
}
//2. 호출은 되지만, null이 들어간다!
@Autowired
public void setNoBean2(@Nullable Member noBean2){
System.out.println("noBean2 = " + noBean2);
}
//3. 자바8에서 제공하는 Optional : 빈이 없으면 Optional.empty를 넣는다!
//Optional 안에 값이 감싸져있다고 생각!
@Autowired
public void setNoBean3(Optional<Member> noBean3){
System.out.println("noBean3 = " + noBean3);
}
}
}