Junior — Middle
Can the Singleton pattern be implemented in multiple ways within the Spring Framework?
sobes.tech AI
Answer from AI
In Spring Framework, the Singleton pattern is implemented by default for beans, as the default scope is singleton. However, Singleton can be implemented in several ways:
- Using a Spring Bean with singleton scope (by default):
@Component
public class MySingletonBean {
// Spring guarantees a single instance
}
- Implementing the classic Singleton pattern with a private constructor and a static method:
public class MySingleton {
private static final MySingleton INSTANCE = new MySingleton();
private MySingleton() {}
public static MySingleton getInstance() {
return INSTANCE;
}
}
- Using enum for Singleton:
public enum MySingletonEnum {
INSTANCE;
// methods
}
In the context of Spring, it is usually enough to declare a bean with singleton scope, but if a classic Singleton outside of Spring is needed, other methods can be used.