The Java singleton is scoped by the Java class loader, the Spring
singleton is scoped by the container context.
Which basically means that, in Java, you can be sure a singleton
is a truly a singleton only within the context of the class loader which loaded
it. Other class loaders should be capable of creating another instance of it
(provided the class loaders are not in the same class loader hierarchy),
despite of all your efforts in code to try to prevent it.
In Spring, if you could load your singleton class in two different
contexts and then again we can break the singleton concept.
So, in summary, Java considers something a singleton if it cannot
create more than one instance of that class within a given class loader,
whereas Spring would consider something a singleton if it cannot create more
than one instance of a class within a given container/context.
A Java singleton, per the design pattern where instantiation is
restricted to one, usually per JVM class
loader by the code.
A Spring singleton bean can be any
normal class you write, but declaring it's scope as singleton means that Spring
will only create one instance and provide its reference to all beans that
reference the declared bean. You may have many instances of that class in your
application, but only one will be created for that bean. You may
even have multiple beans of the same class all declared as singleton. Each bean
will create exactly one instance of the class.
No comments:
Post a Comment