10. Constructor Injection : Secondary Data Injection

Here we use <constructor-arg index="2" ref="addr">

Example
StudentBean.java
package bean;

public class StudentBean {
       private int sno;
       private String name;
       private AddressBean bean;
      
       public StudentBean(){
              System.out.println("Def. const");
       }
             
       public StudentBean(int sno, String name, AddressBean bean)
       {
              System.out.println("Param. const");
              this.sno = sno;
              this.name = name;
              this.bean = bean;
       }
      
       public void getData(){
              System.out.println(sno+": "+name+" : "+bean.getCity());
       }

}

AddressBean.java
package bean;

public class AddressBean {
private String city;
public void setCity(String city) {
       this.city = city;
}
public String getCity() {
       return city;
}
}


MainClass.java
package main;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import bean.StudentBean;

public class MainClass {
       public static void main(String[] args) {
              BeanFactory factory = new ClassPathXmlApplicationContext("res/s.xml");
              StudentBean bean = (StudentBean) factory.getBean("ob");
              bean.getData();
       }

}

s.xml
<beans>      
   <bean id="addr" class="bean.AddressBean">
   <property name="city" value="VIJAYAWADA"></property>  
   </bean>

       <bean id="ob" class="bean.StudentBean">
              <constructor-arg index="0" value="100"/>
              <constructor-arg index="1" type="java.lang.String" value="Satya"/>
              <constructor-arg index="2" ref="addr"></constructor-arg>

       </bean>
</beans>


Output
************************************************
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Param. const
100: Satya : VIJAYAWAD.net.preferIPv4Stack=false

Post a Comment

Thank You

Previous Post Next Post