Spring Factory Bean

factory-bean in spring facilitates to create bean by factory class. Factory class will have non- static methods to return the object of bean. Factory class must have a static method to return the instance of class itself. Below the example to understand factory-bean.

User.java File

package com.jtechies;

public class User {
	public User(){
		System.out.println("User object");
	}
}

Login.java File

package com.jtechies;

public class Login {
	public Login(){
		System.out.println("Login object");
	}
}

Factory.java File

package com.jtechies;

public class Factory {
	private static User user= new User();
	private static Login login= new Login();
	private static Factory service= new Factory();
	
	public  User getUser(){
		return user;
	}
	public  Login getLogin(){
		return login;
	}
	public static Factory getFactory(){
		return service;
	}
}

Test.java File

package com.jtechies;

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

public class Test {
   public static void main(String[] args) {
     ApplicationContext context = new
     	ClassPathXmlApplicationContext("Beans.xml");
     context.getBean("user");
     context.getBean("login");
   }
}

Beans.xml file

<?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-3.0.xsd">

   <bean id="service" class="com.jtechies.Factory"
   	factory-method="getFactory"/>
   <bean id="user" factory-bean="service"
   	factory-method="getUser"/>
   <bean id="login" factory-bean="service"
   	factory-method="getLogin"/>
</beans>

Output

User object
Login object