Saturday, March 19, 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.


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="" xmlns:xsi="" xsi:schemaLocation="">

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


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 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");




This was the example

No comments:

Post a Comment