태그 보관물: Dependency Injection

DI(Dependency Injection)에 대해서..

객체가 스스로 참조하는 객체를 생성하지 않고, 외부 환경(컨테이너)에서 삽입 되는 형태를 DI(Dependency Injection)라고 한다. 그리고, DI를 구현하는 방법은 2가지가 있다.

1. 생성자(Constructor) 방식

public class Shop {   
  private final StockManager stockManager;   
  private final String shopZipCode;   
  public Shop(StockManager stockManager, String shopZipCode) {   
       this.stockManager = stockManager;   
       this.shopZipCode = shopZipCode;   
  }   
}

2. 세터(Setter) 방식

public class Shop {   
  StockManager stockManager;   
  String shopZipCode;   
  /**  
  * @service name="StockManager"       
  */  
  public void setStockManager(StockManager stockManager) {   
      this.stockManager = stockManager;   
  }   
  /**  
  * @config name="shopZipCode"       
  */  
  public void setStockManager(String shopZipCode) {   
      this.shopZipCode= shopZipCode;   
  }   
  // TODO - Joe - how does setter injector do config ? Same way?   
  public void initialize() {   
      // all setXXXs are now done  
  }   
}