Spring Autowiring – Setter Injection

Spring Autowiring – Setter Injection

We have previously discussed an example of Setter Dependency Injection (SDI) using an XML file. In the previous case, we have defined the property name for the dependency injection inside the bean-config file (applicationContext.xml).

Now, we are going to create an example of Setter Dependency Injection (SDI) using @Autowired annotation. With @Autowired annotation, Spring will automatically inject the setter method of the beans.

Example of Auto-wiring using Setter Injection

The Fortune.java and Coach.java are two interfaces that consist of unimplemented methods. The GoodLuckFortune.java and Cricket_Coach.java are the Component classes that implement the Fortune and Coach interfaces, respectively.

Following are the steps to create an example of Autowiring using the Setter Dependency Injection:

Fortune.java

public interface Fortune {
public String fortuneService();
} 

GoodLuckFortune.java

import org.springframework.stereotype.Component;
@Component
public class GoodLuckFortune implements Fortune{
public String fortuneService() {
return "Goodluck for Today..!!" ;
}
} 

Coach.java

public interface Coach {
public String workout();
public String getDailyFortune();
} 

Cricket_Coach

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Cricket_Coach implements Coach {
private Fortune fortuneservice;
// defining the setter method
@Autowired
public void setFortuneservice(Fortune fortuneservice) {
this.fortuneservice = fortuneservice; 
System.out.println( "Autowiring Dependency Injection using Setter: Setter Method" );
}
public String workout() {
return "daily 1 hour of running " ;
}
public String getDailyFortune() { 
return fortuneservice.fortuneService();
}
} 

In the above code, we have defined the @Autowired annotation just above the setter method as we are using the Setter Dependency Injection (SDI).

applicationContext.xml

http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

 
 

App.java

import org.springframework.context.support.ClassPathXmlApplicationContext;
 public class App 
 {
Public static void main( String[] args )
{
ClassPathXmlApplicationContext appcontext = new ClassPathXmlApplicationContext("applicationContext.xml");
Coach co = appcontext.getBean("cricket_Coach", Coach.class);
System.out.println("Autowiring Dependency Injection using Setter Method" + co.getDailyFortune());
System.out.println("Autowiring Dependency Injection using Setter Method" + co.workout());
appcontext.close();
}
}

OUTPUT

applicationContext.xml