의존관계 주입 방법
의존관계 주입은 크게 4가지 방법이있다.
- 생성자 주입
- 수정자 주입(Setter 주입)
- 필드 주입
- 일반 메서드 주입
생성자 주입
- 이름그대로 생성자를 통해서 의존관계를 주입받는 방법이다.
특징
- 생성자 호출시점에 딱 1번만 호출되는 것이 보장된다.
- 불변, 필수 의존관계에 사용
@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;
}
}
※ 생성자가 1개일시 @Autowired 어노테이션 생략이 가능하다.
수정자 주입(Setter 주입)
- setter라 불리는 필드의 값을 변경하는 수정자 메서드를 통해서 의존관계를 주입하는 방법이다.
특징
- 선택, 변경 가능성이 있는 의존관계에 사용
- 자바빈 프로퍼티 규약의 수정자 메서드 방식을 사용하는 방식이다.
@Component
public class OrderServiceImpl implements OrderService{
private MemberRepository memberRepository;
private DiscountPolicy discountPolicy;
@Autowired
public void setMemberRepository(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
@Autowired
public void setDiscountPolicy(DiscountPolicy discountPolicy) {
this.discountPolicy = discountPolicy;
}
}
※ '@Autowired'의 기본동작은 주입할 대상이 없으면 오류가 발생한다. 주입할 대상이 없어도 동작하게 하려면 (required = false)로 지정하여야한다.
필드 주입
특징
- 코드가 간결하지만, 외부에서 변경이 불가능해서 테스트 하기 힘들다는 치명적인 단점이있다.
- DI 프레임워크가 없으면 아무것도 할 수 없다.
@Component
public class OrderServiceImpl implements OrderService{
@Autowired private final MemberRepository memberRepository;
@Autowired private final DiscountPolicy discountPolicy;
}
일반 메서드 주입
- 일반 메서드를 통해서 주입 받을수 있다.
특징
- 한번에 여러 필드를 주입 받을 수 있다.
- 일반적으로 잘 사용하지 않는다.
▶ 의존관계 자동주입은 스프링 컨테이너가 관리하는 스프링 빈이여야 동작한다. 스프링 빈이 아닌 Class의 경우 '@Autowired' 코드를 적용해도 아무 기능도 동작하지않는다.
생성자주입이 권장되는 이유
불변
- 대부분의 의존관계 주입은 한번 일어나면 애플리케이션 종료시점까지 의존관계를 변경 할 일이 없다.
오히려 의존관계는 애플리케이션 종료 전 까지 변하면 안된다. - 생성자 주입은 객체를 생성할때 딱 1번만 호출되므로 이후에 호출되는 일이 없다.
누락
- 생성자 주입시 파라메타 누락시 인지가 가능하다.(컴파일 오류)
final 키워드
- 생성자 주입을 사용하면 final 키워드를 사용할 수 있다.
옵션처리
- 주입할 스프링 빈이 없어도 동작해야 할 때가 있다.
- 그런데 '@Autowired'만 사용하면 'required' 의 기본값이 'true' 로 되어 있어서 자동 주입 대상이 없으면 오류가 발생한다.
자동주입 대상을 옵션으로 처리하는 방법
- '@Autowired(required = false)' : 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출 안됨.
- @Nullable : 자동 주입할 대상이 없으면 null이 입력된다.
- Optional<> : 자동 주입할 대상이 없으면 Optional.empty 가 입력된다.
'@Autowired(required = true)'(기본값 사용시)
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'autowiredTest.TestBean': Unsatisfied dependency expressed through method 'setNoBean1' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'hello.core.member.Member' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
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);
}
}
}
결과
noBean3 = Optional.empty
noBean2 = null
※ Member는 스프링 빈이 아니다.
▶ 이전 프로젝트 개발시에는 스프링 컨테이너, 빈, 의존관계에 대한 세부적인 개념이없었는데 조금씩 정리가 되어간다.
▶Lombok을 활용한 생성자 주입으로 하자!