Setter Injection overrides the values injected by Constructor Injection in Spring

By | September 17, 2017

Setter injection overrides Constructor injection:

If we write both setter injection and constructor injection for the same property then setter injection will override the values provided by constructor injection.

Example:

Create a Dynamic Web Project in Eclipse IDE

Add the following jars:-

  • commons-logging.jar
  • spring-beans.jar
  • spring-core.java

Create MyFactory.java

package mypack;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
 public class MyFactory {
   private static BeanFactory beanFactory; 
   public static BeanFactory getBeanfactory(){
     return beanFactory; 
   }
   static{ 
     Resource r=new ClassPathResource("applicationContext.xml");
     beanFactory=new XmlBeanFactory(r);
   } 
}

Create SIOverrides.java

package mypack;
 public class SIOverrides{
   private String empName;
   private int Id;
   SIOverrides(int Id,String empName){
     System.out.println("inside constructor with two args.");
     this.Id=Id;
     this.empName=empName; 
   } 
   public void setEmpName(String empName){
     this.empName = empName;
   } 
   public void setId(int id){
     Id = id; 
   } 
   public String toString(){
     return "Id is: "+Id+"\n"+"Employee Name is: "+empName; 
   }
}

Create User.java

package mypack;
import org.springframework.beans.factory.BeanFactory; 
 public class User{ 
   public static void main(String[] args){ 
     BeanFactory beanFactory=MyFactory.getBeanfactory(); 
     System.out.println("Requesting demo Bean"); 
     SIOverrides bean=(SIOverrides)beanFactory.getBean("demo"); 
     System.out.println(bean); 
   } 
}

Create applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
  xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- bean config -->
<bean id="demo" class="mypack.SIOverrides">
  <constructor-arg value="100"/>
  <constructor-arg>
  <value>XYZ</value>
  </constructor-arg>
  <property name="Id" value="1"/>
  <property name="empName">
  <value>ABC</value>
  </property>
</bean>
</beans>

Result:

Run User class as Java application.

Leave a Reply