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 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 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;


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"

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


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.
import org.springframework.core.io.ClassPathResource;

public class MainTest {

public static void main(String[] args) {
ApplicationContext appContext = new 

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


Lucknow is capital of UP