Video in progress
Spring beans are singletons by default. Is that the same thing as the GoF Singleton?
No. The GoF Singleton means the class itself enforces a single instance inside the JVM (more precisely, the classloader). A Spring singleton means "one bean per ApplicationContext"; the class itself is ordinary, and you can create as many objects of it as you like with new.
📖 Answer
The difference is easy to see in code:
@Service
public class PriceService { } // no private constructor, no getInstance()
// the Spring context will have only one PriceService bean
// but in a test you can freely write new PriceService()
The advantages of the Spring approach:
- the class isn't tied to static state, so in a test you can create it as an ordinary object or mock it;
- you can even make two beans from one class (with
@Bean, using different names and settings); - if two contexts are started, each one has its own instance.
A common follow-up question in interviews: "is a singleton bean thread-safe?" No, not automatically. All requests use the one instance at the same time, so keeping mutable fields inside a bean (for example, private int counter) is dangerous. Beans are usually written stateless.
Sign up to mark studied questions and save your progress.