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

Example

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

EmployeeFactory.java


package com.answersz.factorymethods;

public class EmployeeFactory {

 private EmployeeService employeeService = new EmployeeService();

 public EmployeeService getEmployeeService() {
 return employeeService;
 }

}


EmployeeService.java

package com.answersz.factorymethods;

public class EmployeeService {

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

}


factoryBean.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="employeeFactory" class="com.answersz.factorymethods.EmployeeFactory" />
 <bean id="employeeService" factory-bean="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 bean attribute

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

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

 empService.save();

 }
}


Output

Save
Employee

 


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 *

*