Dependency Injection for Spring 3 & after Spring version 2.5

Dependency Injection for Spring 3 & after Spring version 2.5


Posted in : Spring Posted on : November 23, 2011 at 6:49 PM Comments : [ 0 ]

Under this heading, you will find the dependency injection after Spring version 2.5 or in simpler words, the dependency injection using annotations. This section contains example code of Setter Injection.

Dependency Injection for Spring 3 & after Spring version 2.5

Under this heading, you will find the dependency injection after Spring version 2.5 or in simpler words, the dependency injection using annotations. This section contains example code of Setter Injection.

Dependency Injection or Inversion of control

The Inversion of control or Dependency Injection is the Spring feature which give us the concept that you don't need to create object but need to describe how they should be created. Also, you need to configure (in a XML ) which service is use by which component and don't need to link each component with related services. The IOC(Inversion of control) container do all this for you.

After Spring 2.5, the annotation changed the scenario and reduce the overhead of XML configuration. Now, you can configure the dependency injection via annotations.

When you implement @Autowired annotation, it searches the Spring bean (class) which implements this interface and put it automatically into the setter.

The code for the helper class using setter method with annotation is given below :

package com.devmanuals.output;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.devmanuals.output.IOProducer;

@Service
public class HelperClass
{
IoProducer outputProducer;

@Autowired
public void setOutputProducer(IoProducer outputProducer){
this.outputProducer = outputProducer;
}
public void run() {
String s = "This is my test";
outputProducer.writer(s);
}
}

The @Autowired annotation searches the Spring bean (class) which implements this interface and put it automatically into the setter and create a object of it. After that you can use this object to call class function ,which implements the interface, as given below :

package com.devmanuals.output;

import org.springframework.stereotype.Service;

@Service
public class NiceWriter implements IoProducer {
public void writer(String s) {
System.out.println("The string is " + s);
}
}

 

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics