Dependency Injection is a very popular Design pattern. It was earlier called Inversion of Control.
Explanation of Dependency Injection with an Example
Example.
The PersistenceManager class is used to persist objects to database
1 2 3 4 5 6 7 8 9 10 | public class PersistenceManager { public void store(Object obj) { Contect ctx=new InitialContext(); DataSource ds=(DataSource)ctx.lookup(“java:/comp/env/jdbc/myDataSource”); Connection con=ds.getConnection() } } |
In the above example we have hardcoded the jndi name . It is not that all application will use the same jndi name. According to Dependency injection design pattern dependency should be injected to the using component.Here a DataSource object should be passed to the PersistenceManager instead of forcing it to create.
1 2 3 4 5 6 7 8 9 10 11 12 | public class PersistenceManager { private ce ds; PersistenceManager(Datasource ds) { this.ds=ds; } public void store(Object object) { Connection con=ds.getConnection(); } } |
Now PersistenceManager is decoupled from DataSource so PersistenceManager becomes more reusuable
The User of the PersistenceManager class knows better what DataSource to use then the programmer. So the user will provide the DataSource instance whileusing the PersistenceManager.
DependencyInjection can used not only with constructor but also through setter methods in the PersistenceManager class.
Struts2 uses DependencyInjection to set the action properties with the request parameters.
So one won’t have to worry about populating the properties and can work on them present inside a method of the action.
Leave a Reply