Download presentation
1
Java EE - Dependency Injection -
Pierre-Johan CHARTRE
2
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.” 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
3
Example: A hight coupling app
MyScreen <<Servlet>> MyService <<Object>> MyDAO <<Object>> MyObject <<Object>> uses uses uses uses OracleDriver <<jar>>
4
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
5
How to remove coupling ? Using the Factory Design Pattern ?
6
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>>
7
Dependency Injection « OK, we removed coupling, but it will be better if it’s dynamic ! » It’s « Inversion of Control » (IoC)
8
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 …
9
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
10
J2EE is a standard ! JSR 330: Dependency Injection for Java
private IService service; A J2EE is one JSR, multiple implementations WELD OpenWebBeans Google Guice Spring …
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.