What is Singleton with factory-method in Spring Framework with Example
7417 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
Open Eclipse
Click on menu New -> Others
In wizards type "Java Project" and Select "Java Project"
Click Next
Enter project name as "SingletonFactoryMethodExample", then click Next
Goto Libraries tab, then click on Add External JARs, then select Spring's 21 Framework Jars and commons-logging-1.1.jar.
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;
}
}