Dependency Injection

Download Report

Transcript Dependency Injection

Java EE
- Dependency Injection Pierre-Johan CHARTRE
[email protected]
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
MyService
<<Servlet>>
MyDAO
<<Object>>
uses
MyObject
<<Object>>
uses
<<Object>>
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
IDAO
<<Object>>
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
MyTestDAO MyDAOOracle
<<Object>>
<<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
IService
<<Servlet>>
IDAO
<<Object>>
MyObject
<<Object>>
uses
uses
MyTestService
MyService
<<Object>>
<<Object>>
<<Object>>
uses
uses
MyTestDAO MyDAOOracle
<<Object>>
3 Configurations
•1 for screen testing
•1 for service testing
•1 for DAO testing
<<Object>>
OracleDriver
<<jar>>
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
…