Example
1. Create a POJO class (Emp.java)
package com.r4r;
public class Emp {
private String address;
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
} }
2. Create Beans configuration file (r4rBean.xml)
<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-2.5.xsd">
<bean id="r4rempbean" class="com.r4r.Emp">
<property name="name" value="Hello bean Factory"/>
</bean>
</beans>
3. Create a Main program (EmpMain.java)
package com.r4r;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class EmpMain {
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("r4rBean.xml"));
Emp obj = (Emp) factory.getBean("r4rempbean");
System.out.println(obj.getName());
} }
4. Output: Hello bean Factory
There are following two important points to note about the main
program:
1 First step is to create factory object where we used framework API
XmlBeanFactory() to create the factory bean and ClassPathResource()
API to load the bean configuration file available in CLASSPATH. The
XmlBeanFactory() API takes care of creating and initializing all the objects
ie. beans mentioned in the configuration file.
2 Second step is used to get required bean using getBean() method of the created bean factory object. This method uses bean ID to return a generic object which finally can be casted to actual object. Once you have object, you can use this object to call any class method.