본문 바로가기

Spring

Spring- 옵션 선택

옵션 처리

  • @Autowired(required=false) : 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출 안됨
  • org.springframework.lang.@Nullable : 자동 주입할 대상이 없으면 null이 입력된다.
  • Optional<> : 자동 주입할 대상이 없으면 Optional.empty 가 입력된다.

 스프링 빈이 등록되어있지 않은 경우

package hello.core.autowired;

public class AutowiredTest {

    @Test
    void AutowiredOption(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class);
    }

    @Component
    static class TestBean{
        //Member 객체는 스프링 빈으로 등록 안 되어있음

        @Autowired(required = false)  // (스프링 빈이 없으면) 메소드 호출 안됨
        public void setNoBean1(Member noBean1){
            System.out.println("noBean1 = " + noBean1);
        }

        @Autowired  // (스프링 빈이 없으면) 메소드 호출은 되는데 null이 들어감
        public void setNoBean2(@Nullable Member noBean2){
            System.out.println("noBean2 = " + noBean2);
        }

        @Autowired  // (스프링 빈이 없으면) Optional.empty가 넣어짐
        public void setNoBean3(Optional<Member> noBean3){
            System.out.println("noBean3 = " + noBean3);
        }
    }
}


noBean3 = Optional.empty
noBean2 = null

 스프링 빈이 등록되어 있는 경우

package hello.core.autowired;

public class AutowiredTest {

    @Test
    void AutowiredOption(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class);
    }

    @Component
    static class TestBean{

        @Bean  //Member 객체를 스프링 빈으로 등록한 경우
        static Member member(){
            return new Member(1L, "memberA", Grade.VIP);
        }

        @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  // (스프링 빈 있으면) Optinal로 빈이 감싸짐
        public void setNoBean3(Optional<Member> noBean3){
            System.out.println("noBean3 = " + noBean3);
        }
    }
}


noBean3 = Optional[hello.core.member.Member@6e4566f1]
noBean1 = hello.core.member.Member@6e4566f1
noBean2 = hello.core.member.Member@6e4566f1