Monday, June 18, 2012

Create beans with factory method (singleton class) in spring


Mostly the beans that are configure in the spring application context will be created by calling one of the class's constructor.
In the case of configuring singleton class(class that only create one instance) or bean  allowing throw factory method.
Here illustrate a example to understand it-
Directory Structure-

Class FactoryBean.java
package com.test;

public class FactoryBean {
private String name;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private FactoryBean(){}

private static class SingaltonClass                // inner class who create only single instance
{
static FactoryBean instance=new FactoryBean();
}
public static FactoryBean getInstance()            // factory method to create instance
{
return SingaltonClass.instance;

}
public void show()
{
System.out.println("Name is="+name);
}

}

class Main.java
package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String args[])
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
FactoryBean fact=ctx.getBean("factoryBean", FactoryBean.class);
fact.show();
}
}

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="factoryBean" class="com.test.FactoryBean" factory-method="getInstance">
<property name="name" value="Factory Beans"></property>
</bean>
</beans>



Output is=
Name is=Factory Beans



For Further Reading,
General, Java, spring

0 comments:

Post a Comment


 

Site Status

Man Behind Technical Today

Hello, I am Navin Bansal. I am a student of MCA in Rajsthan Institute of Engineering and Technology and owner of this blog. I share my view and ideas among people.