User DocumentationOne minute descriptionTwo minute tutorial Five minute introduction Advanced Topics FAQ Container Components Terminology Mock Objects Inversion of Control Types PatternsInversion of ControlDependency Injection Constructor Injection Setter Injection Interface-Impl Separation Lifecycle Antipatterns Developer DocumentationHow To ContributeRelative Volunteering Release Process Project InformationSloganMailing lists Source Repositories Open Issues Blog entries Statistics Team Sister Projects TShirts MiscellaneousDifferentiatorsNirvana Full Sitemap |
Constructor InjectionAuthors: Paul Hammant, Aslak Hellesoy OverviewConstructor 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:
![]() ![]() OriginRachel 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.Examplepublic 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 for Constructor Injector Shop shop = new Shop(myStockManager); Container supportPicoContainer was the first container to support and popularize this for of dependency injection. Spring Framework has been retroffitted with constructor capability, but its primary focus is still constructor injection. Even Avalon's reference container has been upgraded to have compatibility with constructor injection components. |