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
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.
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.
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.