1. 의존관계 주입 방법
- 의존관계 주입은 4가지 방법이 있다.
(1) 생성자 주입
- 생성자를 통해서 의존 관계를 주입받는 방법
- 특징
- 생성자 호출시점에 딱 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을 생략 가능
(2) 수정자 주입(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;
}
}
자바 빈 프로퍼티
자바에서는 필드의 값을 직접 변경하지 않고 setter, getter 메서드를 통해서 값을 읽거나 수정하는 규칙을 만들었다. 이것이 자바 빈 프로퍼티 규약이다.
(3) 필드 주입
- 필드에 바로 주입하는 방법
- 특징
- 코드가 간결해서 많은 개발자들을 유혹하지만 외부에서 변경이 불가능해서 테스트 하기 힘들다는 단점이 있다.
- DI 프레임워크가 없으면 아무것도 할 수 없다.
- 사용하지 않는다
- 애플리케이션의 실제 코드와 관계 없는 테스트 코드
- 스프링 설정 목적으로 하는 @Configuration 같은 곳에서만 특별한 용도로 사용
@Component
public class OrderServiceImpl implements OrderService {
@Autowired
private MemberRepository memberRepository;
@Autowired
private DiscountPolicy discountPolicy;
}
(4) 일반 메서드 주입
- 일반 메서드를 통해서 주입 받을 수 있다.
- 특징
- 한번에 여러 필드를 주입받을 수 있다.
- 일반적으로 잘 사용하지 않는다.
@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;
}
}
2. 옵션 처리
- 주입할 스프링 빈이 없어도 동작해야 할 때가 있다.
- @Autowired만 사용하면 required 옵션의 기본값이 true로 되어 있어서 자동 주입 대상이 없으면 오류가 발생한다.
- 자동 주입 대상 옵션을 처리하는 방법
- @Autowired(required = false) : 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출 안됨
- org.springframework.lang.@Nullable : 자동 주입할 대상이 없으면 null이 입력된다.
- Optional <> : 자동 주입할 대상이 없으면 Optional.empty가 입력된다.
옵션 처리 Test코드
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 setNoNean1(Member member) {
System.out.println("setNoNean1; = " + member);
}
@Autowired
public void setNoNean2(@Nullable Member member) {
System.out.println("setNoNean2; = " + member);
}
@Autowired(required = false)
public void setNoNean3(Optional<Member> member) {
System.out.println("setNoNean3; = " + member);
}
}
}
Test코드 결과
- Member는 스프링 빈이 아니다.
- setNoBean1()은 @Autowired(required=false)이므로 호출 자체가 안된다.
3. 정리
생성자 주입을 선택해라!!
최근에는 스프링을 포함한 DI 프레임워크 대부분이 생성자 주입을 권장한다.
- 불변
- 대부분의 의존관계 주입은 한번 일어나면 애플리케이션 종료 시점까지 의존관계를 변경할 일이 없다.
- 수정자 주입을 사용할 경우 setter 메소드를 public으로 열어두어야 한다. 변경하면 안 되는 메서드를 열어두는 것은 지양해야 한다.
- 생성자 주입은 객체를 생성할 때 딱 1번만 호출되므로 이후에 호출되는 일이 없다. 따라서 불변하게 설계할 수 있다.
- 누락
- 생성자 주입을 사용하면 주입 데이터 누락했을 때 컴파일 오류가 발생한다.
- final 키워드
- 생성자 주입을 사용하면 필드에 final 키워드를 사용할 수 있다.
- 생성자에서 값이 설정되지 않는 오류를 컴파일 시점에서 막아준다.
기본으로 생성자 주입을 사용하고, 필수 값이 아닌 경우에는 수정자 주입 방식을 옵션으로 부여한다.
본 글은 김영한 님의 "스프링 핵심 원리"(인프런) 유료 강의를 들으며 요약, 정리하고 일부 정보를 추가 작성한 것입니다.
반응형
'Spring(JAVA Framework) > Spring Core' 카테고리의 다른 글
Lombok 라이브러리 (0) | 2021.08.19 |
---|---|
@ Autowired 사용시 조회 빈이 중복되는 경우 (0) | 2021.08.19 |
컴포넌트 스캔 (Component Scan) (0) | 2021.08.18 |
Singleton (싱글톤) (0) | 2021.08.18 |
BeanDefinition (스프링 빈 설정 메타 정보) (0) | 2021.08.18 |
댓글