Friday 18 March 2011

BeanFactory Interface

A bean factory is an implementation of the Factory design pattern. A bean factory is a general-purpose factory which creates and hold many types of beans. It is a class whose responsibility is to create and dispense beans. There are several implementations of BeanFactory in Spring. The most commonly used implementation is org.springframework.beans.factory.xml.XmlBeanFactory. The following example will show how to use the XmlBeanFactory and BeanFactory to create the beans.

Example:-

Lets take the bean TestBean which has toString() method. The code for the bean is as follows:-

package com.vaani.spring.beans

public class TestBean {

public String toString(){

return "Bean has been called";

}

}


 

The corresponding metadata file :

<?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-2.5.xsd">

<bean id="test" class="com.vaani.spring.beans.TestBean" />

</beans>


The Beanfactory Interace example class is as follows:-

package com.vaani.spring.factory;
//--
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;

import com.vaani.spring.beans.TestBean;

public class BeanFactoryExample {

public static void main (String [] ar){

Resource res = new FileSystemResource("com/vaani/xml/spring-beans.xml");

BeanFactory factory = new XmlBeanFactory(res);

TestBean bean = (TestBean)factory.getBean("test");

System.out.println(bean.toString());

}

}

This was the example




No comments:

Post a Comment