User Documentation

One minute description
Two minute tutorial
Five minute introduction
Advanced Topics
FAQ
Container
Components
Terminology
Mock Objects
Inversion of Control Types

Patterns

Inversion of Control 
Dependency Injection 
Constructor Injection 
Setter Injection 
Interface Implementation Separation 
Lifecycle 
Antipatterns

Developer Documentation

 Current build status
How To Contribute
Relative Volunteering
Release Process

Project Information

Slogan
Mailing lists
Source Repositories
Open Issues
Blog entries 
Statistics
Team
Sister Projects
TShirts

Miscellaneous

Differentiators
Nirvana

Full Sitemap

Feeds


Site
News
Constructor Injection

Authors: Paul Hammant, Aslak Hellesoy

Overview

Constructor Injection is a Dependency Injection variant where an object gets all its dependencies via the constructor. This is PicoContainer's most important feature.

The most important benefits of Constructor Injection are:

  • It makes a strong dependency contract
  • It makes testing easy, since dependencies can be passed in as Mock Objects
  • It's very succinct in terms of lines of code
  • Classes that rely on Constructor Injection are generally Good Citizens
  • A dependency may be made immutable by making the dependency reference final

Martin Fowler explains Constructor Injection in more detail.


PicoContainer also supports Setter Injection.

Origin

Rachel Davies, while reviewing Joe's book, left a Fermat-like margin note when view a snippet like the above. "Why not use constructors ?". Brilliant and simple.

Example

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.

Using Constructor Injector Components Without a Container.

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);

Container support

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 Avalon's reference container has been upgraded to have compatibility with constructor injection components.