1 . In general we do not need to implement one custom factory bean , as the spring IOC container has the most factory bean classes implemented for the most of the cases .
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.
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<bean class="com.ramesh.common.CustomFactoryBean">
</bean></beans>
now in the main class
package com.ramesh.common; import org.springframework.beans.factory.FactoryBean; public class CustomerFactoryBean implements FactoryBean { private Customer customer = new Customerundefined); @Override public Object getObjectundefined) throws Exception { // TODO Auto-generated method stub return customer; } @Override public Class<Customer> getObjectTypeundefined) { // TODO Auto-generated method stub return Customer.class; } @Override public boolean isSingletonundefined) { // TODO Auto-generated method stub return true; } }and now spring application context file
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<bean class="com.ramesh.common.CustomFactoryBean">
</bean></beans>
now in the main class
public static void main(String[] args) { System.out.println("...Loading beans..."); AbstractApplicationContext context = new ClassPathXmlApplicationContext("context.xml"); System.out.println("...fetch Customerto get Object...."); Customer myBean=context.getBean(Customer.class); myBean.doTask(); }