Home  >  Spring Core

Example of factory-method in Spring

By Arvind Rai, April 07, 2013
In spring if a class has private constructor and we want to initialize that bean, then factory-method will be used. In this case the bean must have static method that will return the object of containing class.

XML for factory-method

Spring provides factory-method attribute in bean tag. We need to assign instance method of factory class using factory-method in our application context file.
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-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
     
    <bean id="userService" class="com.concretepage.UserService" factory-method="createInstance">
    </bean>
</beans> 



Service Class and Main method to run Demo

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
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us