Junior — Middle
What is the difference between using the singleton pattern within Spring and the standard singleton implementation in Java?
sobes.tech AI
Answer from AI
In the standard implementation of the singleton pattern in Java, a class is created with a private constructor and a static method that returns the only instance of this class. This requires manual control of thread safety and object lifecycle management.
In Spring, the singleton is implemented at the container level: by default, beans are created as singletons, meaning one instance per Spring context. Spring manages the creation and lifecycle of the object, ensures thread safety, and dependency injection.
Main differences:
- Lifecycle management: in Spring — container-managed, in standard Java — manual.
- Thread safety: Spring guarantees it, standard singleton requires additional synchronization.
- Dependency injection: in Spring, singleton can have dependencies that are automatically injected.
Example of a standard singleton in Java:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
In Spring, simply declare a singleton bean:
@Service
public class MyService {
// Spring will create one instance per context
}