Home  >  Spring Core

FactoryBean by ampersand (&) in spring

By Arvind Rai, April 25, 2013
In spring, FactoryBean can be fetched in java by ampersand. Spring container can provide us actual FactoryBean instance. For this we need to fetch bean with prefix ampersand. See below.
FactoryBean factoryBean=(FactoryBean)context.getBean("&customfb");
 
Find the sample example.
SpringAppDemo.java
package com.concretepage;
import org.springframework.beans.factory.FactoryBean;
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) throws Exception {
		AbstractApplicationContext  context = new ClassPathXmlApplicationContext("app-test.xml");
	    FactoryBean factoryBean=(FactoryBean)context.getBean("&customfb");
	    MyBean myBean = (MyBean)factoryBean.getObject();
	    myBean.doTask();
		
	}
}  




CustomFactoryBean.java
package com.concretepage.test;
import org.springframework.beans.factory.FactoryBean;
import com.concretepage.test.MyBean;
public class CustomFactoryBean implements FactoryBean {
	private MyBean myBean=new MyBean();
	@Override
	public MyBean getObject() throws Exception {
		return myBean;
	}
	@Override
	public Class<? extends MyBean> getObjectType() {
		return myBean.getClass();
	}
	@Override
	public boolean 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 id="customfb" class="com.concretepage.test.CustomFactoryBean"  />
      
</beans> 
Output
Object of MyBean is created.
do some task. 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us