August 27 2015

Spring factory method attribute

Spring factory method attribute

A spring bean can be instantiated using static factory method. A method that returns instance of a class is called factory method. The spring container uses the static factory method to instantiate the bean. The class name of the factory method has to be specified using ‘class’ attribute and the factory method name has to be specified using ‘factory-method’ attribute of the bean element.

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


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

package com.answersz.factorymethods;

public class EmployeeService {

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


package com.answersz.factorymethods;

public class EmployeeFactory {

 private static EmployeeService employeeService = new EmployeeService();

 public static EmployeeService getEmployeeService() {
 return employeeService;



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

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


package com.answersz.factorymethods;

import org.springframework.context.ApplicationContext;

public class FactoryBeanTest {

 public static void main(String[] args) {

 // Spring factory method attribute

 ApplicationContext context = new ClassPathXmlApplicationContext(

 EmployeeService empService = (EmployeeService) context



Save Employee

Copyright © 2014. All rights reserved.

Posted August 27, 2015 by answersz in category Spring

Leave a Comment

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