이번 챕터는 다양한 의존관계 주입 방법과 주의 할 점을 설명해준다.





다양한 의존관계 주입 방법

의존 관계는 크게 4가지 주입 방법이 있다.

  • 생성자 주입
  • 수정자 주입(setter 주입)
  • 필드 주입
  • 일반 메소드 주입

이제 이 4가지 주입 방법에 대해 알아보도록 한다.

생성자 주입

  • 이름 그대로, 생성자를 통해 의존 관계를 주입 받는 방법이다.
  • 특징
    • 생성자를 호출하는 시점에 딱 1번만 호출되는 것이 보장된다.
    • 불변, 필수 의존관계에 주로 사용된다.(개발자는 웬만하면 값을 채워넣어야 한다고 생각한다.)

중요 : 생성자가 딱 1개만 있으면(생상자 오버로딩X) @Autowired를 생략해도 자동으로 주입된다. 물론 스프링 빈에만 해당된다.

package hello.core.order;

import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.discount.RateDiscountPolicy;
import hello.core.member.Member;
import hello.core.member.MemberRepository;
import hello.core.member.MemoryMemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OrderServiceImpl implements OrderService{

    private final MemberRepository memberRepository;
    private final DiscountPolicy discountPolicy;

    //@Autowired 생성자가 딱 하나일때는 @Autowired가 필요없다
    public OrderServiceImpl(MemberRepository memberRepository, 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);
        Order order = new Order(memberId, itemName, itemPrice, discountPrice);

        return order;

    }
}

수정자 주입

  • setter라 불리우는 필드의 값을 변경하는 수정자 메서드를 통해서 주입받는 방법이다.
  • 특징
    • *선택,변경**이 있는 의존관계에서 주로 사용한다.(선택적으로 의존관계 주입)
    • 자바빈 프로퍼티 규약의 수정자 메서드 방식을 사용하는 것을 말한다.
package hello.core.order;

import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.discount.RateDiscountPolicy;
import hello.core.member.Member;
import hello.core.member.MemberRepository;
import hello.core.member.MemoryMemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OrderServiceImpl implements OrderService{



    private  MemberRepository memberReponsitory;
    private  DiscountPolicy discountPolicy;

    @Autowired
    public void setMemberReponsitory(MemberRepository memberReponsitory) {
        this.memberReponsitory = memberReponsitory;
    }
    @Autowired
    public void setDiscountPolicy(DiscountPolicy discountPolicy) {
        this.discountPolicy = discountPolicy;
    }

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

        return order;

    }
}

참고 : 생성자 주입은, 스프링 빈 생성과 동시에 의존관계를 주입하는 것에 반해, 생성자 주입은 먼저 스프링 빈을 생성하고 그 후에 의존관계를 주입한다.
@Autowired의 기본 동작은 주입할 대상이 없으면 오류가 발생한다. 주입할 대상이 없어도 동작하게 하려면 @Autowired(required=false)로 지정하면 된다.(선택적 의존관계 주입)

필드 주입

  • 이름 그대로 필드에 주입하는 방식이다.(private임에도 바로 주입이 가능하다!)
  • 특징
    • 코드가 매우매우 간결해진다. 하지만 외부에서 변경이 불가능하다는 치명적인 단점이 존재한다.
    • DI프레임워크가 없으면 아무것도 할 수 없다.
    • (결론) 사용하지 말자.
      • 애플리케이션의 실제 코드와 관계없는 테스트 코드
      • 스프링 설정을 목적으로 하는 @Configuration같은 곳에서만 특수한 상황에서 사용한다.
@Autowired private final MemberRepository memberRepository;
@Autowired private final DiscountPolicy discountPolicy;

일반 메서드 주입

  • 일반 메서드를 통해 주입받는다.
  • 특징
    • 한번에 여러 필드를 주입받을 수 있다.
    • 위 방법으로 다 적용이 가능하기에, 잘 쓰이지는 않는다.




옵션 처리

  • 주입 할 스프링 빈이 없어도 동작해야 할 때가 있다.
  • 그런데 @Autowired만 사용하면 required=true로 되어있어, 자동 주입 대상이 없을 경우 오류가 발생한다. 이러한 오류를 해결하기 위해 아래 세가지 방법으로 해결할 수 있다.
  • @Autowired(required=false):자동 주입할 대상이 없으면 수정자 메서드 자체가 호출 안됨
  • org.springframework.lang.@Nullable : 자동 주입할 대상이 없으면 null로 입력된다.
  • Optional<> : 자동 주입할 대상이 없으면 Optional.empty 가 입력된다.
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.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import java.util.Optional;

public class AutowiredTest {

    @Test
    void AutowiredOption(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class);
    }

    static class TestBean{

        //의존관계가 없어 이 메소드 자체가 호출이 안됨
        @Autowired(required = false)
        public void setNoBean1(Member member){
            System.out.println("member = " + member);
        }


        //호출은 되고싶은데 대상이 없으면 null로 출력된다.
        @Autowired
        pubic void setNoBean2(@Nullable Member member){
            System.out.println("member = " + member);
        }

        //호출은 되고싶은데 대상이 없으면 optioanl.empty로 출력된다.
        @Autowired
        public void setNoBean3(Optional<Member> member){
            System.out.println("member = " + member);
        }

        
        
    }

}

  • Member는 스프링 빈이 아니다.(빈으로 등록 안함)

참고 : @Nullable, Optional은 스프링 전반에 걸쳐 지원된다. 예를 들어 생성자 자동 주입에서 특정 필드에만 사용해도 된다.




생성자 주입을 선택해라!

과거에는 수정자 주입과 필드 주입을 많이 사용했지만, 최근에는 스프링을 포함한 DI프레임워크 대부분이 생성자 주입을 권장한다.

불변

  • 대부분의 의존관계 주입은 한 번 일어나면 애플리케이션 종료시점까지 의존관계를 변경 할 일이 없다. 오히려 대부분의 의존관계는 애플리케이션 종료 전까지 변하면 안된다.(불변해야 한다)
  • 수정자 주입을 사용하면, setXxx 메소드를 public으로 열어두어야 한다. 이는 즉, 누군가 실수로 변경 할 수 있고, 변경하면 안되는 메소드를 열어두는 것은 좋은 설계 방법이 아니다.
  • 생성자 주입은 객체를 생성할 때 딱 한 번만 호출되므로 불변하게 설계 할 수 있다.

누락

  • 실무에서는 프레임워크없이 순수한 자바 코드를 단위 테스트 하는 경우가 많다. 다음과 같이 수정자 의존 관계일 경우, NullPointException이 발생 할 수 있다. 의존관계 주입이 누락되었기 때문이다.
  • 하지만 생성자 주입을 이용하면, 컴파일시 오류가 나므로 개발자가 코드 작성중 의존관계가 필요하다는 사실을 알 수 있다.
  • 또한 생성자 주입을 사용하면 final 키워드를 사용 할 수 있다.(즉 생성자에서만 값을 넣어 줄 수 있다)

final 키워드

  • 생성자 주입에서만 final키워드를 사용 할 수 있다. 이는 곧, 객체 생성 누락을 방지 할 수 있다는 것을 의미한다.(생성자에서 혹시라도 값이 설정되지 않는 오류를 컴파일 시점에서 막아준다)

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


정리

  • 생성자 주입 방식을 선택하는 이유는 여러가지가 있지만, 프레임워크에 의존하지 않고 순수한 자바 언어의 특징을 잘 살리는 방법이기도 하다.
  • 기본으로 생성자 주입을 사용하고, 필수 값이 아닌 경우에만 수정자 주입 방식을 옵션으로 부여하면 된다. 생성자 주입과 수정자 주입을 동시에 사용 할 수 있다.
  • 항상 생성자 주입을 선택해라! 가끔 옵션이 필요하면 수정자 주입을 선택하고… 필드 주입은 선택하지 말자.


롬복과 최신 트렌드

막상 개발을 해보면, 대부분이 다 불변이고 그래서 생성자에 final 키워드를 사용하게 된다. 그런데 생성자도 만들어야 하고, 주입받은 값을 대입해야 하는 코드도 작성해야 하는 번거로움이 존재한다. 이를 해결하기 위해 롬복이 등장한다!

</br>

기존 코드

package hello.core.order;

import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.discount.RateDiscountPolicy;
import hello.core.member.Member;
import hello.core.member.MemberRepository;
import hello.core.member.MemoryMemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

    //@Autowired 생성자가 딱 하나일때는 @Autowired가 필요없다
    public OrderServiceImpl(MemberRepository memberRepository, 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);
        Order order = new Order(memberId, itemName, itemPrice, discountPrice);

        return order;

    }
}

  • 이제 롬복을 적용해보자.
  • 롬복이 제공하는@RequiredArgsConstructor를 사용하면 final이 붙은 필드를 모아 생성자를 자동으로 생성해준다.(코드에는 보이지 않지만 실제 호출 가능하다.)
  • 소스가 훨씬 간결해진다.
package hello.core.order;

import hello.core.discount.DiscountPolicy;
import hello.core.member.Member;
import hello.core.member.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor // final(필수 값)이 붙은 argument를 토대로 생성자를 만들어준다. cmd+f12를 통해 확인 할 수 있다.
public class OrderServiceImpl implements OrderService{

    private final MemberRepository memberRepository;
    private final DiscountPolicy discountPolicy;

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

        return order;

    }
}

롬복이 자바의 애노테이션 프로세서라는 기능을 이용하여 컴파일 시점에 생성자 코드를 자동으로 생성해준다. 실제 class를 디컴파일 해보면 확인 할 수 있다.

정리

최근에는 생성자를 딱 1개만 두고, @Autowired를 생략하는 방법을 주로 사용한다.
여기에 Lombok 라이브러리의 RequiredArgsConstructor를 사용하면 기능은 다 제공하면서 훨씬 간결한 코드를 작성 할 수 있다.




조회 빈이 2개 이상 - 문제

@Autowired는 빈의 타입으로 조회한다. 마치 아래와 유사하다. ac.getBean(DiscountPolicy.class
하지만 만약, DiscountPolicy를 구현한 FixDiscountPolicyRateDiscountPolicy를 빈으로 등록하면 어떻게 동작하게 될까? 그럴 경우 스프링에서 친절하게 오류로그로 안내해준다.

NoUniqueBeanDefinitionException: 
No qualifying bean of type 'hello.core.discount.DiscountPolicy' available: expected single matching bean but found 2: fixDiscountPolicy,rateDiscountPolicy

이 때 하위 타입으로 빈을 지정할 수 있지만, 이러한 방식은 DIP를 위배하고 유연성이 떨어진다.
그리고 이름만 다르고 완전히 똑같은 타입의 스프링 빈이 2개 있는 케이스는 근본적으로 해결하지 못한다.
스프링 빈을 수동으로 등록해서 해결 할 수 있지만, 이보다 더 나은, 의존 관계 자동 주입에서 해결하는 여러가지 방법이 존재한다.(다음 강의에 이어서….)




@Autowired 필드명, @Qualifier, @Primary

조회되는 빈이 2개 이상 발생 할 때, 아래 세가지 방식으로 해결 할 수 있다.

  • @Autowired 필드명 매칭
  • @Qualifier -> @Qualifier끼리 매칭 -> 빈 이름 매칭
  • @Primary 사용

이제 이 세가지 방법에 대해 하나하나 알아보자.



@Autowired필드명 매칭

@Autowired는 타입 매칭을 먼저 시도하고, 여러 빈이 존재할경우 필드이름, 파라미터 이름으로 추가 매칭한다.

기존코드 :

@Autowired
private DiscountPolicy discountPolicy

필드 명을 빈 이름으로 변경

@Autowired
private DiscountPolicy rateDiscountPolicy

이렇게 되면 필드명이 rateDiscountPolicy이므로 정상 주입된다. @Autowired의 주입 순서는 아래와 같다.

  1. 타입 매칭
  2. 타입 매칭 결과가 2개 이상일 때 필드 명 혹은 파라미터 명으로 빈 이름 매칭



@Qualifier 사용

@Qualifier는 추가 구분자를 붙여주는 방법이다. 주입시 추가적인 옵션을 제공하는 것이지, 빈 이름을 변경하는 것은 아니다.

빈 등록시 @Qualifier 사용

@Component
@Qualifier("mainDiscountPolicy")
public class RateDiscountPolicy implements DiscountPolicy {}

생성자 자동 주입 예시

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

수정자 자동 주입 예시

@Autowired
public DiscountPolicy setDiscountPolicy(@Qualifier("mainDiscountPolicy") DiscountPolicy discountPolicy) {
      return discountPolicy;
}

@Qualifier로 주입시 이에 맵핑된 빈을 못찾게 된다면 이 이름을 가진 빈을 추가로 찾는다. 하지만 @Qualifier@Qualifier를 찾는 용도로만 사용하는게 명확하고 좋다.

  • @Qualifier 주입 순서
    • @Qualifier끼리 매칭
    • 빈 이름으로 매칭
    • NoSuchBeanDefinitionException이라는 예외 발생



@Primary 사용

@Primary는 우선순위를 정하는 방법이다. @Autowired시에 여러번 매칭되면 @Primary가 우선권을 가진다.

예시 코드를 보자 :

@Component
@Primary
public class RateDiscountPolicy implements DiscountPolicy {}

@Component
public class FixDiscountPolicy implements DiscountPolicy {}

이 때는 RateDiscountPolicy가 우선권을 가지게 된다.

####@Primary, @Qualifier 활용 코드에서 자주 사용하는 메인 데이터베이스의 커넥션을 획득하는 스프링 빈이 있고, 코드에서 특별한 기능 으로 가끔 사용하는 서브 데이터베이스의 커넥션을 획득하는 스프링 빈이 있다고 생각해보자. 메인 데이터 베이스의 커넥션을 획득하는 스프링 빈은 @Primary 를 적용해서 조회하는 곳에서 @Qualifier 지정 없이 편리하게 조회하고, 서브 데이터베이스 커넥션 빈을 획득할 때는 @Qualifier 를 지정해서 명시적으로 획 득 하는 방식으로 사용하면 코드를 깔끔하게 유지할 수 있다. 물론 이때 메인 데이터베이스의 스프링 빈을 등록할 때 @Qualifier 를 지정해주는 것은 상관없다.

우선순위

@Primary 는 기본값 처럼 동작하는 것이고, @Qualifier 는 매우 상세하게 동작한다. 이런 경우 어떤 것이 우선권을 가져갈까? 스프링은 자동보다는 수동이, 넒은 범위의 선택권 보다는 좁은 범위의 선택권이 우선 순위가 높다. 따라서 여기서도 @Qualifier 가 우선권이 높다.




##애노테이션 직접 만들기
실무에서 가끔씩 사용한다. 위에서 만든 @Qualifier("mainDiscountPolicy)와 같이 적게 되면, 타입 체크가 안된다. 다음과 같이 애노테이션을 만들어 해결할 수 있다.

애노테이션 생성 코드 :

package hello.core.annotation;

import org.springframework.beans.factory.annotation.Qualifier;

import java.lang.annotation.*;

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Qualifier("mainDiscountPolicy")
public @interface MainDiscountPolicy {
}

생성자 주입 코드 :

package hello.core.order;

import hello.core.annotation.MainDiscountPolicy;
import hello.core.discount.DiscountPolicy;
import hello.core.member.Member;
import hello.core.member.MemberRepository;
import org.springframework.stereotype.Component;

@Component

public class OrderServiceImpl implements OrderService{

    private final MemberRepository memberRepository;
    private final DiscountPolicy discountPolicy;

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



애노테이션은 상속이라는 개념이 없다. 이렇게 여러 애노테이션을 모아서 사용하는(=>새로운 애노테이션 생성) 기능은 스프링이 지원해주는 기능이다.
@Qualifier뿐 아니라, 다른 애노테이션도 함꼐 조합하여 사용할 수 있다.




조회한 빈이 모두 필요할 때, List, Map

의도적으로 정말 해당 타입의 스프링 빈이 다 필요한 경우가 있다.
예를 들어 할인 서비스를 제공하는데, 클라이언트가 할인의 종류를 선택할 수 있다고 가정해보자.
스프링을 사용하게되면 전략 패턴을 통해 쉽게 구현할 수 있다.

package hello.core.autowired.allbean;

import hello.core.AutoAppConfig;
import hello.core.discount.DiscountPolicy;
import hello.core.member.Grade;
import hello.core.member.Member;
import org.assertj.core.api.Assertions;
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 java.util.List;
import java.util.Map;

public class AppBeanTest {

    @Test
    void findAllBean(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(AutoAppConfig.class, DiscountService.class);
        //여러 config를 등록할 떄는 위와 같이 설정해주면 됨

        DiscountService discountService = ac.getBean(DiscountService.class);
        Member member = new Member(1L, "userA", Grade.VIP);
        int discountPrice = discountService.discount(member, 10000, "fixDiscountPolicy");

        Assertions.assertThat(discountService).isInstanceOf(DiscountService.class);
        Assertions.assertThat(discountPrice).isEqualTo(1000);

        int rateDiscountPrice = discountService.discount(member, 20000, "rateDiscountPolicy");
        Assertions.assertThat(rateDiscountPrice).isEqualTo(2000);

    }

    static class DiscountService {
        private final Map<String, DiscountPolicy> policyMap;
        private final List<DiscountPolicy> policies;

        @Autowired
        public DiscountService(Map<String, DiscountPolicy> policyMap, List<DiscountPolicy> policies) {
            this.policyMap = policyMap;
            this.policies = policies;

            System.out.println("policyMap = " + policyMap);
            System.out.println("policies = " + policies);
        }

        public int discount(Member member, int price, String discountCode) {
            DiscountPolicy discountPolicy = policyMap.get(discountCode);
            return discountPolicy.discount(member,price);
        }
    }
}


로직 분석

  • DiscountService는 Map으로 모은 DiscountPolicy를 주입받는다. 이 때 fixDiscountPolicyRateDiscountPolicy가 주입받는다.
  • discount()메소드에서는 전달받은 discountCode

주입 분석

  • Map<String, DiscountPolicy> : map의 key의 스프링 빈 이름을 넣어주고, value 값에 해당 빈의 실 객체를 넣어준다.
  • List<DiscountPolicy> : DiscountPolicy타입으로 조회한 모든 스프링 빈을 담아준다.
  • 만일 해당하는 객체가 없다면, 빈 컬렉션이나 Map을 주입한다.




자동, 수동의 올바른 실무 운영 기준

편리한 자동 기능을 기본으로 사용하자
그러면 어떤 경우에 컴포넌트 스캔 및 자동 주입을 사용하, 어떤 경우에 설정정보를 통해 수동으로 빈을 등록하고 의존관계도 주입할까?
결론적으로, 점점 자동을 선호하는 추세다. @Component뿐 아니라 @Controller, @Service, @Repository등 계층에 맞추어 일반적인 애플리케이션 로직을 자동으로 스캔할 수 있도록 지원한다. 거기에 스프링 부트는 컴포넌트 스캔을 기본으로 사용하고, 스프링 부트의 다양한 스프링 빈들도 조건이 맞으면 자동으로 등록하도록 설계되어 있다.
설정 정보를 기반으로 애플리케이션을 구성하는 부분과 실제 동작하는 부분을 명확하게 나누는 것이 이상이지만, 개발자 입장에선 스프링 빈 등록시 @Component만 등록하면 끝날 일을 @Configuaration 빈을 적고, 객체 생성 및 주입 대상을 적어주는 과정은 번거롭다. 또 관리할 빈이 많아 설정정보가 방대해지면 이 configuration을 관리하는 것 자체가 일이다.
그리고 려정적으로 자동 빈 등록을 사용해도 OCP, DIP를 지킬 수 있다.

그럼 수동 빈 등록은 언제 사용하면 좋을까?
애플리케이션은 크베 업무 로직과 기술 지원 로직으로 분리할 수 있다.

  • 업무 로직 빈 : 웹을 지원하는 컨트롤러, 핵심 비즈니스 로직이 있는 서비스, 데이터 계층 로직을 처리하는 리포지토리 등이 모두 업무 로직 빈이다. 보통 비즈니스 요구사항을 개발할 때 추가하거나 변경된다.
    • 업무로직은 숫자도 많고, 한 번 개발해야 하면 컨트롤러, 서비스, 리포지토리처럼 유사한 패턴이 있다. 이런 경우 자동 기능을 적극적으로 사용하는 것이 좋다. 보통 문제가 발생해도 어떤 곳에서 문제가 발생했는지 명확하게 파악하기 쉽기 때문이다.
  • 기술 지원 빈 : 기술적인 문제나 공통 관심사(AOP)를 처리할 떄 주로 사용된다. 데이터베이스 연결이나, 공통 로그 처리 처럼 업무 로직을 지원하기 위한 하부 기술이나 공통 기술들이다.
    • 기술 지원 로직은 업무 로직 대비 그 수가 매우 적고, 보통 애플리케이션 전반에 걸쳐 광범위하게 영향을 미친다. 그리고 업무 로직은 문제가 발생했을 때 어디가 문제인지 명확하게 잘 드러나지만, 기술 지원 로직은 적용이 잘 되고 있는지 아닌지 조차 파악하기 어려운 경우가 많다. 그래서 이런 기술 지원 로직은 수동 빈 등록을 사용해서 명확하게 드러내는게 좋다.


애플리케이션에 광범위하게 영향을 미치는 기술 지원 객체는 수동 빈으로 등록해서 설정정보에 명확하게 나타나게 하는 것이 유지보수 하기 좋다


비즈니스 로직 중에서 다형성을 적극 활용할 때에는 수동 빈 등록을 이용한다. 앞서 조회한 빈이 모두 필요할 때, List와 Map을 통해서 작성한 코드를 보자. 만일 신규 개발자가 투입되서 해당 코드에서 어느 빈들이 주입될 지 파악해야 할 떄, 코드만 보고 한 번에 파악하기는 쉽지 않다. 타고타고 들어가서 파악을 해야하는 번거로움이 존재하며, 여러 코드를 찾아봐야 한다.


이런 경우 수동 빈으로 등록하거나, 혹 자동으로 하려면 특정 패키지에 같이 묶어두는게 좋다. 핵심은, 다른사람이 딱 보고 이해가 되어야 한다는 것이다.
아래 코드는 별도의 설정정보를 만들고 수동으로 빈을 등록한 것이다.

@Configuration
public class DiscountPolicyConfig{
	@Bean
	public DiscountPolicy rateDiscountPolicy() {
		return new RateDiscountPolicy();
	}
	@Bean
	public DiscountPolicy fixDiscountPolicy() {
		return new FixDiscountPolicy();
	}
}

위와 같이 설정 정보만 봐도 한 눈에 빈의 이름은 물론이고, 어떤 빈들이 주입될지 파악할 수 있다. 그래도 빈 자동등록을 사용하고 싶으면 파악하기 좋게 DiscountPolicy의 구현 빈들만 모아서 특정 패키지에 모아두자.

참고: 스프링 및 스프링 부트가 자동으로 등록하는 수많은 빈들은 예외다.
이런 부분들은 스프링 자체를 이해하고 스프링의 의도대로 잘 사용하는 것이 중요하다. 스프링 부트의 경우 DataSource같은 데이터베이스 연결에 사용하는 기술 지원 로직까지 내부에서 자동으로 등록하는데, 이 부분은 메뉴얼을 잘 참고해서 스프링 부트가 의도한 대로 사용하면 된다.
반면, 스프링 부트가 아니라 내가 직접 기술지원 객체를 스프링 빈으로 등록한다면 수동으로 등록해 명확하게 드러내는 것이 좋다


  • @Component@Bean의 차이점?
  • @Bean은 수동으로 스프링 컨테이너에 직접 등록할 빈을 등록하는 것이고, @Component는 자동으로 스프링 컨테이너에 스프링 빈을 등록하는 기능이다. 용도가 다르다고 생각하면 된다.

앞선 내용은 김영한 강사님의 스프링 핵심 원리 기본편 강의를 들으며 정리한 내용입니다.


oksusutea's blog

꾸준히 기록하려고 만든 블로그