본문으로 바로가기

[SPRING] 다양한 의존관계 주입 방법

category SPRING/기본 문법 2021. 4. 27. 15:03

1. 생성자 주입을 선택하라!

의존관계 주입은 총 4가지로 나뉜다.

 

1. 생성자 주입

- 생성자 호출시점에 딱 1번만 호출되는 것이 보장된다.

- 불변, 필수 의존관계에 사용

 

중요! 생성자가 딱 1개만 있으면 @Autowired를 생략해도 자동 주입 된다. 물론 스프링 빈에만 해당한다

 

* 불변

대부분의 의존관계 주입은 한번 일어나면 애플리케이션 종료시점까지 의존관계를 변경할 일이 없다.

오히려 대부분의 의존관계는 애플리케이션 종료 전까지 변하면 안된다.(불변해야 한다.)

수정자 주입을 사용하면, setXxx 메서드를 public으로 열어두어야 한다.

 

누군가 실수로 변경할 수 도 있고, 변경하면 안되는 메서드를 열어두는 것은 좋은 설계 방법이 아니다.

생성자 주입은 객체를 생성할 때 딱 1번만 호출되므로 이후에 호출되는 일이 없다.

 

따라서 불변하게 설계할 수 있다.

 

* 선언방법 

@Component
public class OrderServiceImpl implements OrderService {
	
    // 불변 final 선언
    private final MemberRepository memberRepository;
    private final DiscountPolicy discountPolicy;

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

    @Override
    public Order createOrder(Long memberId, String itemName, int itemPrice) {
        Member member = memberRepository.findById(memberId);
        int discountPrice = discountPolicy.discount(member, itemPrice);

        return new Order(memberId, itemName, itemPrice, discountPrice);
    }

    public MemberRepository getMemberRepository() {
        return memberRepository;
    }
}

 

잘 보면 필수 필드인 discountPolicy 에 값을 설정해야 하는데, 이 부분이 누락되었다.

자바는 컴파일 시 점에 다음 오류를 발생시킨다. java: variable discountPolicy might not have been initialized 기억하자! 컴파일 오류는 세상에서 가장 빠르고, 좋은 오류다!

 

참고: 수정자 주입을 포함한 나머지 주입 방식은 모두 생성자 이후에 호출되므로, 필드에 final 키워드를 사용할 수 없다. 오직 생성자 주입 방식만 final 키워드를 사용할 수 있다

2. Setter주입 (수정자 주입)

- 선택, 변경 가능성이 있는 의존관계에 사용

- 자바빈 프로퍼티 규약의 수정자 메서드 방식을 사용하는 방법이다

 

* 선언방법 

@Component
public class OrderServiceImpl implements OrderService {
 	private MemberRepository memberRepository;
 	private DiscountPolicy discountPolicy;
    
    // Setter주입
 	@Autowired
 	public void setMemberRepository(MemberRepository memberRepository) {
 		this.memberRepository = memberRepository;
 	}
    
    // Setter주입
 	@Autowired
 	public void setDiscountPolicy(DiscountPolicy discountPolicy) {
 		this.discountPolicy = discountPolicy;
 	}
}

참고 : @Autowired 의 기본 동작은 주입할 대상이 없으면 오류가 발생한다. 주입할 대상이 없어도 동작하게 하려면               @Autowired(required = false) 로 지정하면 된다

 

3. 필드 주입

- 이름 그대로 필드에 바로 주입하는 방법이다. (비추천)

- 코드가 간결해서 많은 개발자들을 유혹하지만 외부에서 변경이 불가능해서 테스트 하기 힘들다는 치명 적인 단점이 있다.

- DI 프레임워크가 없으면 아무것도 할 수 없다.

- 사용하지 말자!

- 애플리케이션의 실제 코드와 관계 없는 테스트 코드 스프링 설정을 목적으로 하는

   @Configuration 같은 곳에서만 특별한 용도로 사용

 

* 선언방법

@Component
public class OrderServiceImpl implements OrderService {
 	@Autowired
 	private MemberRepository memberRepository;
 	@Autowired
 	private DiscountPolicy discountPolicy;
}

4. 일반 메서드 주입

- 한번에 여러 필드를 주입 받을 수 있다.

- 일반적으로 잘 사용하지 않는다.

 

스프링을 포함한 DI 프레임워크, 그 중에서도 생성자 주입을 권장한다.

 

* 선언방법

@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;
 	}
}

 

참고: 어쩌면 당연한 이야기이지만 의존관계 자동 주입은 스프링 컨테이너가 관리하는 스프링 빈이어야 동작한다.

       스프링 빈이 아닌 Member 같은 클래스에서 @Autowired 코드를 적용해도 아무 기능도 동작하지 않는다.

 

옵션 처리

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

그런데 @Autowired 만 사용하면 required 옵션의 기본값이 true 로 되어 있어서 자동 주입 대상이 없으면

오류가 발생한다. 자동 주입 대상을 옵션으로 처리하는 방법은 다음과 같다.

 

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

Optional<> : 자동 주입할 대상이 없으면 Optional.empty 가 입력된다

 

예제 확인

 

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);
        }
		
        // 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);
        }
    }
}

내용 정리

생성자 주입 방식을 선택하는 이유는 여러가지가 있지만, 프레임워크에 의존하지 않고,

순수한 자바 언어의 특징을 잘 살리는 방법이기도 하다.

 

기본으로 생성자 주입을 사용하고, 필수 값이 아닌 경우에는 수정자 주입 방식을 옵션으로 부여하면 된다.

생성자 주입과 수정자 주입을 동시에 사용할 수 있다.

 

항상 생성자 주입을 선택해라!

그리고 가끔 옵션이 필요하면 수정자 주입을 선택해라. 필드 주입은 사용하지 않는게 좋다

 

출처 : 김영한의 스프링