Spring Dependency Injection – DI

16 Flares Twitter 0 Facebook 5 Google+ 11 LinkedIn 0 Filament.io 16 Flares ×

Spring uses inversion of control to satisfy dependencies between objects. Traditional approach before Spring framework was to hard code the dependencies and this creates tightly coupled code and there was no easy way to change that. People used to minimize this tight coupling, by resorting to ” programming to an interface and not to an implementation”, but even with that approach, the actual creation of the dependent object was the responsibility of the calling piece of code. Of course there were custom frameworks being developed by various individuals to create some form of ¬†inversion of control to achieve dependency injection ( DI). Spring¬†changed all that by incorporating dependency injection in a framework.

Dependency Injection (DI) – Spring

In Spring framework, Dependency Injection (DI) is used to satisfy the dependencies between objects. It exits in two major types :

  1. Constructor Injection
  2. Setter Injection

Dependency Injection offers atleast the following advantages

  • Loosely couple code
  • Separation of responsibility
  • Configuration and code is separate.

Setter Injection

Spring framework will inject the dependency via a setter method.

XML configuration

Constructor Injection

It is obvious. Here Spring uses the  Constructor and the arguments passed to it to determine the dependency. Rest all is same as setter injection.

XML Configuration

Dependency Injection using Annotations

Since Spring 2.5, it is possible to configure the dependency injection via annotations. In my view you should use this way of configuring your Spring beans.

The important annotation is @Autowired.

[alert style=”white”] @Autowired will instruct Spring framework to look for a bean that implements the required interface and inject it automatically via the setter.[/alert]

XML Configuration