News:

GinGly.com - Used by 85,000 Members - SMS Backed up 7,35,000 - Contacts Stored  28,850 !!

Main Menu

BeanFactory Interface

Started by thiruvasagamani, Sep 23, 2008, 04:19 PM

Previous topic - Next topic

thiruvasagamani

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.visualbuilder.beans;

public class TestBean {

    public String toString(){

                return "Bean has been called";

          }

}


The spring metadata file is spring-beans.xml which is in com/visualbuilder/xml folder.

<?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.visualbuilder.beans.TestBean" />

</beans>



The Beanfactory Interace example class is as follows:-



package com.visualbuilder.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.visualbuilder.beans.TestBean;

public class BeanFactoryExample {

    public static void main (String [] ar){

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

            BeanFactory factory = new XmlBeanFactory(res);

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

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

        }

}


Output :- On running the BeanFactoryExample.java class we have got the following output.

Bean has been called

Jun 1, 2008 1:12:28 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from file [C:\eclipse\workspace\sprinexample\springtutorialexample\com\visualbuilder\xml\spring-beans.xml]
Thiruvasakamani Karnan