Java EE - Dependency Injection - Pierre-Johan CHARTRE pierre-johan.chartre@logica.com
Coupling vs dependency “In computer science, coupling or dependency is the degree to which each program module relies on each one of the other modules.” http://en.wikipedia.org/wiki/Coupling_%28computer_programming%29 Hight coupling (concrete): your dependency is an instance of a concrete class. private ArrayList<String> myList; Low coupling (abstract/interface): your dependency is an instance of an abstract class. private List<String> myList; Limitations: Component replacing, refactoring Test writing, mock Component overriding
Example: A hight coupling app MyScreen <<Servlet>> MyService <<Object>> MyDAO <<Object>> MyObject <<Object>> uses uses uses uses OracleDriver <<jar>>
How to remove coupling ? A solution based on Design Patterns Creation design patterns Factory Singleton Structural design patterns Proxy Architectural design pattern Inversion of Control & Dependency Injection
How to remove coupling ? Using the Factory Design Pattern ?
How to remove coupling ? Service Provider Interface (SPI) the Java 3 approach Define implementations in a text file META-INF/services/com.isima.spi.IDAO com.isima.MyTestDAO com.isima.MyDAOOracle Get implementations ServiceLoader loader = ServiceLoader.load(com.isima.spi.IDAO.class); Iterator iterator = loader.iterator(); while (iterator.hasNext()) { IDAO dao = (IDAO) iterator.next(); dao.find(); } Limitation: static injection IDAO <<Object>> MyTestDAO <<Object>> MyDAOOracle <<Object>>
Dependency Injection « OK, we removed coupling, but it will be better if it’s dynamic ! » It’s « Inversion of Control » (IoC)
Dependency Injection « OK, but we could introduce more features ! » Singleton for only one instance Multiple implementation for the same interface Default implementation AOP Mock for unit tests Annotation support …
Example: A low coupling app MyScreen <<Servlet>> IService <<Object>> IDAO <<Object>> MyObject <<Object>> uses uses uses MyTestService <<Object>> MyService <<Object>> uses MyTestDAO <<Object>> MyDAOOracle <<Object>> OracleDriver <<jar>> 3 Configurations 1 for screen testing 1 for service testing 1 for DAO testing
J2EE is a standard ! JSR 330: Dependency Injection for Java @Inject @InMyServlet private IService service; A J2EE is one JSR, multiple implementations WELD OpenWebBeans Google Guice Spring …