Dependency Injection

Dependency Injection is a very popular Design pattern. It was earlier called Inversion of Control.
Explanation of Dependency Injection with an Example

The PersistenceManager class is used to persist objects to database


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.


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.

Speak Your Mind