의존 관계 자동 주입 상세

박찬우·2023년 12월 17일
0

스프링

목록 보기
16/88

의존 관계 자동 주입

  • 스프링 컨테이너가 관리하는 스프링 빈이어야만 동작한다.
  • 스프링 빈이 아닌 클래스에 @Autowired를 적용해도 아무일도 일어나지 않음

생성자 주입

  • 생성자를 통해서 의존관계 주입
  • 생성자 호출시점에 딱 1번만 호출되는 것을 보장
  • 불변, 필수(final) 의존관계에 사용
  • 생성자가 하나만 있을 경우 @Autowired를 제외해도 동일하게 적용됨(여러개 일 경우 특정 생성자에 애노테이션을 붙여야함)
@Component
public class OrderServiceImpl implements OrderService{

    private final MemberRepository memberRepository;
    private final DiscountPolicy discountPolicy;

    @Autowired
    public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy discountPolicy) {
        this.memberRepository = memberRepository;
        this.discountPolicy = discountPolicy;
    }
}

수정자(setter) 주입

  • setter라 불리는 필드의 값을 변경하는 수정자 메서드를 통해서 의존관계를 주입하는 방법
  • 선택, 변경 가능성이 있는 의존관계에서 사용
  • 주입할 대상이 없는 경우 오류가 나는데 required = false를 사용하면 오류가 나지 않는다
@Component 
public class OrderServiceImpl implements OrderService {
    private MemberRepository memberRepository;    
	private DiscountPolicy discountPolicy;
	
    @Autowired
	//@Autowired(required = false) 주입할 대상이 없는 경우 
	public void setMemberRepository(MemberRepository memberRepository) {
		this.memberRepository = memberRepository;    
	}
	
    @Autowired    
	public void setDiscountPolicy(DiscountPolicy discountPolicy) {
		this.discountPolicy = discountPolicy;    
	}
}

필드 주입

  • 필드에 값을 집어 넣는 것
  • 외부에서 변경이 불가능해서 테스트 하기 힘들다는 치명적인 단점이 있다(직접 접근할 수 있는 방법이 없음)
    • setter의 경우 값을 넣어주면 되고 생성자의 경우 생성 시 넣어주면 됨
  • DI 프레임워크가 없으면 아무것도 할 수 없다(순수 자바코드로는 아무것도 할 수 없음 null 오류가 남)
  • 사용안하는 것을 강력하게 권장
  • 스프링에서만 쓸 경우는 사용하여도 됨(@Configuration, @SpringBootTest) 스프링과 같이 동작하기 때문 그러나 권장하지는 않음
@Component 
public class OrderServiceImpl implements OrderService {

    @Autowired  
	private MemberRepository memberRepository;    
	
	@Autowired    
	private DiscountPolicy discountPolicy;
}

일반 메서드 주입

  • 아무 메서드에나 사용 가능
  • 한번에 여러 필드를 주입 받을 수 있다
  • 일반적으로 잘 사용하지 않음
@Component 
public class OrderServiceImpl implements OrderService {
    private MemberRepository memberRepository;    
	private DiscountPolicy discountPolicy;
	
    @Autowired    
	public void init(MemberRepository memberRepository, DiscountPolicy discountPolicy) {
		this.memberRepository = memberRepository;        
		this.discountPolicy = discountPolicy;    
	}
}

옵션처리

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

        // 호출은 되지만 null로 값이 들어옴
        @Autowired
        public void setNoBean2(@Nullable Member noBean2) {
            System.out.println("noBean2 = " + noBean2);
        }

        // 호출은 도지만 Optional.empty로 값이 들어옴
        @Autowired
        public void setNoBean3(Optional<Member> noBean3) {
            System.out.println("noBean3 = " + noBean3);
        }
    }
}

profile
진짜 개발자가 되어보자

0개의 댓글