Dependency Injection in Spring

Dependency injection involves providing an object its dependencies rather than the object having to acquire those dependencies on its own.

The dependencies are injected into the objects that need them.

The key benefit of dependency injection is Loose coupling.


Spring provides dependency injection by creating associating between components using a concept called “wiring”.

In Spring, we can wire components using XML configurations or by annotation based config file.

Lets assume we have a class Employee that implements a Person interface. Employee has an address.


This is how the Employee class would look like without Dependency Injection:

public class Employee {

private Address address;

public void setAddress(Address address){

this.address = address;


public Address getAddress(){

return address;




In xml configuration file, Spring adds the dependency on Address object as follows :



<bean id=”address” class=”com.techkatak.Address”>

<constructor-arg value=”Temporary Address” />

Here is how the same can be achieved using Java based configurations in Spring.



© 2015, All rights reserved.