Spring DI via setter method

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Setter-based DI is able by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. This technique is considered as the best approach for dependency injection.

Example of Spring DI via setter method

State.java

State is pojo class having some attributes so here state has name and object of Capital class.

package com.javatutsworld;
public class State {
   String stateName;
   Capital capital;
   public String getStateName() {
      return stateName;
    }
   public void setStateName(String stateName) {
      this. stateName = stateName;
   }
   public Capital getCapital() {
      return capital;
   }
   public void setCapital(Capital capital) {
      this.capital = capital;
   }
}

Capital.java

Capital is also pojo class having one attribute called "capitalName".

package com.javatutsworld;

public class Capital {

   String capitalName;

   public String getCapitalName() {
      return capitalName;
    }

  public void setCapitalName(String capitalName) {
    this.capitalName = capitalName;
  }
}

ApplicationContext.xml

this is the configuration file where you need to give the information about your bean class

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org
/schema/beans 
http://www.springframework.org
/schema/beans/spring-beans-3.0.xsd">

 <bean id="StateBean" class="com.javatutsworld.State">
    <property name="stateName" value="UP"/>
    <property name="capital" ref="CapitalBean"/>
  </bean>
 <bean id="CapitalBean" class="com.javatutsworld.Capital">
    <property name="capitalName" value="Lucknow"/>
 </bean>
</beans>

MainTest.java

This MainTest class reads configuration file and print the value of Capital.

package com.javatutsworld;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

public class MainTest {

public static void main(String[] args) {
ApplicationContext appContext = new 
ClassPathXmlApplicationContext("ApplicationContext.xml");

State stateObj = (State) appContext.getBean("StateBean");
String stateName= stateObj.getStateName();
String capitalName= stateObj.getCapital().getCapitalName();
System.out.println(capitalName+"is capital of"+ stateName);
       
}
}

Output

Lucknow is capital of UP
      Advertisements