Constructor Injection is a Dependency Injection variant where an object gets all its dependencies via the constructor.
The most important benefits of Constructor Injection are:
Martin Fowler explains Constructor
Injection
in more detail.
PicoContainer also supports Setter Injection.
Rachel Davies, while reviewing Joe's forthcoming book, left a Fermat-like margin note when looking at a coe sample that used Setter Injection: "Why not use constructors ?". Brilliant and simple. Using constructors per se, is an ordinary OO feature, but having a container that works out what to inject where amongst a list of constructor arguments is something that is useful too.
public class Shop {
private final StockManager stockManager;
private final String shopZipCode;
public Shop(StockManager stockManager, String shopZipCode) {
this.stockManager = stockManager;
this.shopZipCode = shopZipCode;
}
}
Note, for this there is no need to declare needs in any other way. No interfaces, no doclet tags, no external XML. Just your simple component(s) and PicoContainer. No need for post assembly/config initialization either. If it is constructed (not withstanding some asserts on nulls) it has its needs satisfied. Components need not be interface/implementation separated. This is the coder's choice.
The component can be used directly, without any container. The missing dependency scenario is not an issue since it is impossible to instantiate an object without all dependencies being satisfied.
Shop shop = new Shop(myStockManager);
PicoContainer was the first lightweight container to support and popularize this for of dependency injection. Spring Framework has been retrofitted with constructor injection capability, but its primary focus is still setter injection. Even the once heavyweight technologies like Avalon and OSGi moved towards constructor injection.