주입할 스프링 빈이 없어도 동작해야할 때가 있다.

예를 들어 주입 받을 객체가 세개인데 하나의 값은 주입 받지 못하더라도 메서드는 실행될 수 있도록 하고자 할 때가 있다. 

 

그런데 @Autowired를 사용하면  기본값이  required의 값이 true로 설정되어있기 때문에 값이 없으면 오류가 발생한다. 

 

자동 주입 대상을 옵션으로 처리하는 방법은 3가지가 있다. 

  • @Autowired(required=false) 
  • @Nuallable
  • Optional< >

 

테스트 코드를 통해서 위의 옵션들에 따라 어떻게 동작하는지 알아보자

 

public class AutowiredTest {

    @Test
    void autowiredTest() {

        ApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class);

    }

    static class TestBean {

        //호출 안됨
        @Autowired(required = false)
        public void setNoBean1(Member member) {
            System.out.println("setNoBean1 = " + member);
        }

        //null 호출
        @Autowired
        public void setNoBean2(@Nullable Member member) {
            System.out.println("setNoBean2 = " + member);
        }

        //Optional.empty 호출
        @Autowired
        public void setNoBean3(Optional<Member> member) {
            System.out.println("setNoBean3 = " + member);
        }

    }
}

 

//실행결과
setNoBean2 = null
setNoBean3 = Optional.empty

 

 

Member는 스프링이 관리하는 빈이 아니다. 그런데 @Autowired로 객체를 주입받으려고 하고 있다. 

따라서 그냥 @Autowired를 사용한다면 주입해줄 객체가 없으므로 오류가 발생한다. 

 

 Error creating bean with name 'autowiredTest.TestBean': 
 Unsatisfied dependency expressed through method 'setNoBean1' parameter 0: 
 No qualifying bean of type 'hello.core.member.Member' available: 
 expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

 

그래서 우리는 이렇게 주입 받을 객체가 없더라도 오류가 발생하지 않도록 옵션을 설정하는 세가지 방식을 적용해서 테스트 코드를 수행해보는 것이다. 

 

  •  @Autowired ( required=false) 로 설정하는 경우
    true인 경우에는 값이 반드시 들어와야하지만, false로 설정한 경우에는 값이 들어오지 않는다면 메서드 자체가 실행되지 않는다. 그래서 실행결과에서 setBean1의 메서드가 실행되지 않은 것을 알 수 있다. 
  • @Nullable
    주입 받을 객체에 @Nullable를 사용하는 경우, 주입 받는 객체가 없다면 null값을 반환해준다. 
  • Optional< > 
    주입 받을 객체를 Optional로 감싸면 널값이 들어오는경우 Optional.empty 가 출력된다. 

 

 

 

 

+ Recent posts