September 23 2015

Spring factory bean attribute

Spring factory bean attribute

A spring bean can be instantiated using non static factory method. A method that returns instance of a class is called factory method. The spring container uses the non-static factory method to instantiate the bean.

The bean of the factory method’s class has to be specified using ‘factory-bean’ attribute and the factory method name has to be specified using ‘factory-method’ attribute of the bean element.

<bean id=”employeeFactory” class=”com.answersz.factorymethods.EmployeeFactory” />

<bean id=”employeeService” factory-bean=”employeeFactory” factory-method=”getEmployeeService” />


In the below example, getEmployeeService is the non-static factory method in EmployeeFactory class which returns the instance of EmployeeService. The EmployeeService bean can instantiated by configuring ‘factory-bean’ to EmployeeFactory’s bean and factory-method as ‘getEmployeeService ‘.

package com.answersz.factorymethods;

public class EmployeeFactory {

 private EmployeeService employeeService = new EmployeeService();

 public EmployeeService getEmployeeService() {
 return employeeService;


package com.answersz.factorymethods;

public class EmployeeService {

 public void save() {
 System.out.println("Save Employee");



<beans xmlns=""
 xmlns:xsi="" xmlns:util=""

 <bean id="employeeFactory" class="com.answersz.factorymethods.EmployeeFactory" />
 <bean id="employeeService" factory-bean="employeeFactory"
 factory-method="getEmployeeService" />


package com.answersz.factorymethods;

import org.springframework.context.ApplicationContext;

public class FactoryBeanTest {

 public static void main(String[] args) {

 // Spring factory bean attribute

 ApplicationContext context = new ClassPathXmlApplicationContext(

 EmployeeService empService = (EmployeeService) context





Copyright © 2014. All rights reserved.

Posted September 23, 2015 by answersz in category Spring

Leave a Comment

Your email address will not be published. Required fields are marked *