Spring Tutorial Home

  • Managing Database Transactions
  • Remoting in Spring
  • Working with the Web Layer

Spring Home

Java Resources

Community

Site

Instantiating the Beans in Spring


This page will describe how the spring will instatiate a bean from the given metadata in xml file. There are two ways we can instatiate the bean i.e via constructor and via static factory methods. The instantiation using a constructor will be covered in the Constructor Injection Section. Here we will cover the instatiation of the bean using static factory method.


A new attribute factory-method in the <bean> tag specified the factory method which will be called by the Spring to instatiate the object of the bean. For example:-


<bean id="test" class=com.visualbuilder.beans.TestBean" factory-method="createInstance"/>


Example To use the Factory method Instatiation in Spring:-


package com.visualbuilder.beans;


public class TestBean {



private static TestBean bean = null;



public String toString(){

    return "Bean has been called";

}

public static TestBean createInstance(){

  if(bean == null) {

        bean = new TestBean();

       System.out.println("Bean is created");

   }



  return bean;

}

}


<?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" factory-method="createInstance" />


</beans>


 


Output:- On running the ApplicationContextExample.java file we got the following output.


Jun 1, 2008 1:49:48 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh

INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@c4bcdc: display name [org.springframework.context.support.ClassPathXmlApplicationContext@c4bcdc]; startup date [Sun Jun 01 13:49:48 IST 2008]; root of context hierarchy

Jun 1, 2008 1:49:48 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [com/visualbuilder/xml/spring-beans.xml]

Bean is created

Jun 1, 2008 1:49:48 PM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory

INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@c4bcdc]: org.springframework.beans.factory.support.DefaultListableBeanFactory@15e83f9

Jun 1, 2008 1:49:48 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons

INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@15e83f9: defining beans [test]; root of factory hierarchy

Bean has been called

                    

Copyright © 2010 VisualBuilder. All rights reserved