Now that we understand the Spring Dependency Injection and the singleton implementation, and we also know how to configured the class as bean in spring definition file which has the constructor either the default or overridden. Let’s understand how to configure the singleton class in spring.
To highlight the scenario singleton does not have a public constructor (which means new keyword cannot be used to instantiate the object of this class) and has a public static getInstance method to get the instance of the class.
Spring provided the way to configure such classes as beans through the factory methods. Here we will configure the factory-method which is responsible to return the object of the class.
The singleton class would be
The singleton I read in the "Spring in Action" book
package test.patterns;
public class SingltonInner {
private SingltonInner(){}
private static class InnerSingltonInstance{
static SingltonInner singlton = new SingltonInner();
}
public static SingltonInner getInstance(){
return InnerSingltonInstance.singlton;
}
public String getMessage(String name){
return "Hello " + name;
}
}
Java2html
The class using the Singleton
|
Java2html
|
The definition of the beans is in this XML file.
<?xml version="1.0" encoding="UTF-8"?>
<beans> <bean id="factoryInjection" class="test.spring.injection.FactoryInjection"> <property name="singleton"> <ref bean="singltonInner"/> </property> </bean> <bean id="singltonInner" class="test.patterns.SingltonInner" factory-method="getInstance"/> </beans> |
No comments:
Post a Comment