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” />

Example

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 ‘.

EmployeeService.java

package com.answersz.factorymethods;

public class EmployeeService {

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

}

EmployeeFactory.java

package com.answersz.factorymethods;

public class EmployeeFactory {

 private static EmployeeService employeeService = new EmployeeService();

 public static EmployeeService getEmployeeService() {
 return employeeService;
 }

}

factoryMethod.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

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

</beans>

FactoryBeanTest.java

package com.answersz.factorymethods;

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

public class FactoryBeanTest {

 public static void main(String[] args) {

 // Spring factory method attribute

 ApplicationContext context = new ClassPathXmlApplicationContext(
 "factoryMethod.xml");

 EmployeeService empService = (EmployeeService) context
 .getBean("employeeService");

 empService.save();

 }
}

Output


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 *

*