[spring]多種類の依存関係注入(DI)方法



  • インプラント作成者
  • 不変、主に必須依存関係に用いられる
  • final利用可能/コンパイルエラーの原因となる可能性がある
  • 생성자가 1개면 @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)
  • 選択・変更可能な依存関係
     @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;
      }
    }
  • 
    
    - 필드 주입
    
      - 외부에서 변경이 불가능해서 테스트가 힘듦
      - 테스트목적의 특별한 용도에서 사용(코드가 짧음)
      - DI 프레임워크가 없으면 아무것도 안됨
      - 사용 비추천
    
    ```java
    @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;
     }
    }