Let's look at a simple example: you have an application, and you just use the default class loader. You have a class that, for some reason, you decide that there should not be more than one instance in the application. (Think of a scenario where several people are working on parts of an application).
If you do not use the Spring framework, the Singleton pattern ensures that your application will not have more than one instance of the class. This is because you cannot create instances of the class by doing the βnewβ because the constructor is private. The only way to get an instance of a class is to call some static class method (usually called "getInstance"), which always returns the same instance.
Saying that you use the Spring framework in your application, simply means that in addition to the usual methods of obtaining an instance of the class (new or static methods that return an instance of the class), you can also ask Spring to provide you with an instance of this class, and Spring will ensure that everyone the time you request an instance of this class, it always returns the same instance, even if you are not writing the class using the Singleton template, in other words, even if the class has an open constructor, if you always request Spring for An instance of this class, Spring will only call this constructor once during the lifetime of your application.
Normally, if you use Spring, you should use Spring to create instances, and you may have an open constructor for the class. But if your constructor is not private, you do not forbid anyone to create new instances of the class directly, bypassing Spring.
If you really need a single instance of the class, even if you use Spring in your application and define the class in Spring as a singleton, the only way to make sure that the class also implements using Singleton. This ensures that there will be one instance if people use Spring to get an instance or bypass Spring.
inor May 08 '14 at 9:58 a.m. 2014-05-08 09:58
source share