factory-method in Spring XML Configuration

By Arvind Rai, March 09, 2023
In Spring XML configuration, factory-method property of <bean> element, is used to configure factory method. Factory method is used to create an instance of the class.
Find the XML Configuration for factory-method.
<bean 
  id="userService"
  class="com.concretepage.UserService"
  factory-method="createInstance">
</bean> 

Complete Example

spring-config.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.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
     
    <bean id="userService" class="com.concretepage.UserService" factory-method="createInstance">
    </bean>
</beans> 
UserService.java
package com.concretepage;
public class UserService {
	  private static UserService userService = new UserService();
	  private UserService() {
		  System.out.println("Initialising UserService.");
	  }
	  public static UserService createInstance() {
	    return userService;
	  }
} 
SpringDemo.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo {
    public static void main(String... args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
            context.getBean("userService");
    } 
} 
Find the output.
Initialising UserService. 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us