Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a Spring singleton and a Java singeleton(design pattern)? [duplicate]

I am learning Spring framework and currently reading a book about it. In this book it says that a Spring singleton is different from a Java singleton? What does this mean and what are the differences? Thanks

like image 938
Hossein Avatar asked Mar 06 '13 16:03

Hossein


People also ask

What is the difference between Java singleton and Spring singleton?

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.

What is singleton design pattern in Spring?

Singleton pattern says that one and only one instance of a particular class will ever be created per classloader. The scope of a Spring singleton is described as "per container per bean". It is the scope of bean definition to a single object instance per Spring IoC container. The default scope in Spring is Singleton.

What is the difference between Spring singleton scope and Spring application scope?

When beans are application scoped, the same instance of the bean is shared across multiple servlet-based applications running in the same ServletContext, while singleton scoped beans are scoped to a single application context only.

What is singleton design pattern in Java?

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.


1 Answers

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.

like image 176
Edwin Dalorzo Avatar answered Oct 02 '22 15:10

Edwin Dalorzo