↩뒤로가기

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

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(){
        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) : 자동 주입할 대상이 없으면 호출 자체가 안됨.
  2. org.springframework.lang.@Nullable : 호출은 되지만 null값으로 지정된다.
  3. Option<> : Optional.empty가 된다.

Untitled

<aside> 💡 Nullable과 Optional은 스프링 전반에 걸쳐서 지원된다. 예를 들어 생성자 자동 주입에서 특정 필드에만 사용해도 된다.

</aside>