Setter Injection

Authors: Paul Hammant, Aslak Hellesoy, Philipp Meier

Overview

Setter Injection is where the container or embedder hands dependencies to a component via setter methods after instantiation.

Example

Joe Walnes whist working on Java Open Source Programming with other luminaries, started a Setter Injection IoC design. This is marked up with doclet tags (though that is not hard and fast) :
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 :-)
   }
}

The container use the meta-information to resolve all the dependencies. Components need not be interface/impl separated. Developer's choice.

Using Setter Injector Components Without a Container.

Setter Injection components can be used directly, without any container. The component-using class will continue to compile, but at run time it will be apparent that there are missing dependencies. The downside of this is that a developer may miss a setXXX(..) method invocation if they are using the component directly. That is fairly small as a risk as it would clearly be caught in the development cycle. Caught in the development cycle, but maybe obscurely so with a NullPointerException.

Shop shop = new Shop();
shop.setStockManager(myStockManager);

Container support

The Spring Framework project is the best example of a container that supports setter injector. PicoContainer does too, but we really believe that constructor injector is superior.

Refs + Comparison

Setter Injection is a Dependency Injection variant where an object gets all dependencies via setter methods. PicoContainer support this with SetterInjectionComponentAdapter, but the PicoContainer team recommends Constructor Injection.

The advantage of Constructor Injection is that the setting is atomic in a sense that either all or none of the dependencies are set and that it can occur once and only once. With Setter Injection there is the possibility to forget to set some of the dependencies