이번에는 옵션 처리에 대해서 공부해보았다.
예를 들어 주입할 스프링 빈이 없어도 동작해야 될 때가 있다.
그런데 @Autowired 만 사용하면 required 옵션의 기본값이 true로 되어 있어서
자동 주입 대상이 없으면 오류가 발생한다.
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 AutoWiredTeset {
@Test
void AutoWiredOption(){
ApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class);
}
static class TestBean{
@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);
}
}
}
테스트 코드부터 작성해보았다.
콘솔로그만 보면
1.@Autowired(required=false) : 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출이 안됨.
noBean1 출력자체가 안되었다.
의존관계가 없다면 메서드 자체가 호출이 안된다.
2. org.springframework.lang.@Nullable : 자동 주입할 대상이 없으면 null이 입력된다.
호출은 하고싶을때
noBean2가 호출되는것을 볼 수 있다.
대신 null로 들어온다
3. Optinal<> : 자동 주입할 대상이 없으면 Optinal.empty가 입력된다.
Member는 스프링 빈이 아니다.
'웹프로그래밍 > Spring 핵심 원리' 카테고리의 다른 글
37. 롬복과 최신 트렌드 (0) | 2021.08.16 |
---|---|
36. 생성자 주입을 선택하라 (0) | 2021.08.16 |
34. 다양한 의존관계 주입 방법 (0) | 2021.08.12 |
34. 중복 등록과 충돌 (0) | 2021.08.10 |
33. 필터 (0) | 2021.08.10 |