Knowledge Walls
J2EE Technologies Tutorial
Hyderabad, Andhra Pradesh, India
What is Singleton with factory-method in Spring Framework with Example
7158 Views
Singleton 
Singleton Class allows the user to get only one instance not allow to create multiple objects. Only one object can create by the Singleton Classes.

In below example even scope is prototype but factory-method (getInstance) returns same instance from the application context.
Step.1 Start a Java Project with Spring Jars 
  1. Open Eclipse
  2. Click on menu New -> Others
  3. In wizards type "Java Project" and Select "Java Project"
  4. Click Next
  5. Enter project name as "SingletonFactoryMethodExample", then click Next
  6. Goto Libraries tab, then click on Add External JARs, then select Spring's 21 Framework Jars and commons-logging-1.1.jar.
  7. Click Finish.
Step.2 Project Explorer Preview 
FinancialConstants.java
package com.knowledgewalls;

public class FinancialConstants {
    public double PI = 3.14;
    private static FinancialConstants financialConstants = new FinancialConstants();
    
    private FinancialConstants(){}
    public static FinancialConstants getInstance(){
        return financialConstants;
    }
}
bean-configuration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="financialConstants" class="com.knowledgewalls.FinancialConstants" factory-method="getInstance" scope="prototype" />
</beans>
RunMyProblem.java
package com.knowledgewalls;

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

public class RunMyProgram {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean-configuration.xml");
        FinancialConstants financialConstants = (FinancialConstants) context.getBean("financialConstants");
        FinancialConstants financialConstants2 = (FinancialConstants) context.getBean("financialConstants");
        
        System.out.println(financialConstants.getInstance().hashCode());
        System.out.println(financialConstants.getInstance().PI);
        System.out.println(financialConstants2.getInstance().hashCode());
        
    }
}
Output 
2758093
3.14
2758093
Best Lessons of "Spring 3.0 Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details