Followers

springIOC : autowire constructor

Address.java
=============
package myspring;
public class Address {    
private String city;  
private String state;  
private String country;  
public Address(String city, String state, String country) {  
    super();  
    this.city = city;  
    this.state = state;  
    this.country = country;  
}  
  
public String toString(){  
    return city+" "+state+" "+country;  
}  
    
}


Employee.java
==============
package myspring;
public class Employee {
private int id;  
private String name;  
private Address address;//Aggregation
public Employee() {
    System.out.println("default constructor");
}  
  
public Employee(int id, String name, Address address) {    
    this.id = id;  
    this.name = name;  
    this.address = address;  
}  
  
void show(){  
    System.out.println(id+" "+name);  
    System.out.println(address.toString());  
}   
}

Beans.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-4.0.xsd">

    <bean id="addr" class="myspring.Address" >
        <constructor-arg value="Bengaluru"> </constructor-arg>
        <constructor-arg value="Karnataka"> </constructor-arg>
        <constructor-arg value="India"> </constructor-arg>
    </bean>
    <bean id="emp" class="myspring.Employee" autowire="constructor"> 
        <constructor-arg value="111" type="int" > </constructor-arg>
        <constructor-arg value="Hari"> </constructor-arg>
    </bean>
</beans>

Test.java
===========

package myspring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

      public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
          Employee emp = (Employee)context.getBean("emp");
          emp.show();
    }
    
}

No comments:

Post a Comment