Pages

Tuesday, July 27, 2010

Inner Beans

Spring IOC allows Inner Beans declaration. We can declare a bean inside a beans. But, it has few restriction. Inner Beans are like annonymous beans where it is created and used on the fly. this beans cannot be used outside the enclosing beans. So, it is wise to avoid declaring the 'ID' or 'SCOPE' attributes for them. Because, these values will be ignored by the container. Only the enclosing beans can access them.

Employee.java

package com.ioc;
public class Employee {
private String empId;
private Address address;
public Employee(String empId, Address address){
this.empId = empId;
this.address = address;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public String getEmpId() {
return empId;
}

public void setEmpId(String empId) {
this.empId = empId;
}

}

Address.java

package com.ioc;

public class Address {
public Address(){

}
private String street;
private String city;

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

}

Test.java

package com.ioc;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class Test {
public static void main(String args[]){
Resource xmlResource = new FileSystemResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(xmlResource);
Employee employee = (Employee)factory.getBean("employeeBean");
Address address = employee.getAddress();
System.out.println(employee.getEmpId());
System.out.println(address.getCity());
System.out.println(address.getStreet());
}
}

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"
xmlns:p="http://www.springframework.org/schema/p"
< bean id="addressBean" class="com.ioc.Address">
<property name="street">
Street
< /property>
<property name="city">
Bangalore
< /property>
<property name="address">
< bean class="com.ioc.Address">
<property name="street">
Street
< /property>
<property name="city">
Bangalore
< /property>
< /bean>
< /property>
< /bean>
< /beans>


No comments:

Post a Comment