Home  >  Spring Core

Example of Custom FactoryBean in Spring

By Arvind Rai, April 24, 2013
FactoryBean in spring helps to create custom factory bean. Custom factory bean can initialize bean in the same way as we configure in spring XML. The advantage of defining our own custom factory bean is custom initialization. All we need to do that we will write as class implementing FactoryBean and will override all the methods of FactoryBean and this custom factory bean should be registered in spring XML. And then we can fetch the bean as usual initialized by our custom factory bean. Find the complete example.
CustomFactoryBean.java
package com.concretepage.test;
import org.springframework.beans.factory.FactoryBean;
import com.concretepage.test.MyBean;
public class CustomFactoryBean implements FactoryBean<MyBean> {
	private MyBean myBean=new MyBean();
	@Override
	public MyBean getObject() throws Exception {
		System.out.println("inside getObject");
		return myBean;
	}
	@Override
	public Class<? extends MyBean> getObjectType() {
		System.out.println("inside getObjectType");
		return myBean.getClass();
	}
	@Override
	public boolean isSingleton() {
		System.out.println("inside isSingleton");
		return false;
	}
} 

app-test.xml
<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-3.0.xsd ">

  <bean class="com.concretepage.test.CustomFactoryBean"  />
</beans> 
MyBean.java
package com.concretepage.test;
public class MyBean {
	public MyBean(){
		System.out.println("Object of MyBean is created.");
	}
	public void doTask(){
		System.out.println("do some task.");
	}
} 
SpringAppDemo.java
package com.concretepage;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.concretepage.test.MyBean;
public class SpringAppDemo {
	public static void main(String[] args) {
		System.out.println("...Loading beans...");
		AbstractApplicationContext  context = new ClassPathXmlApplicationContext("app-test.xml");
		System.out.println("...fetch MyBean to get Object....");
		MyBean myBean=context.getBean(MyBean.class);
		myBean.doTask();
	}
}   
Output
...Loading beans...
Object of MyBean is created.
inside isSingleton
...fetch MyBean to get Object....
inside getObjectType
inside isSingleton
inside getObject
do some task. 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us