Why Spring Beans Default to Singleton: Benefits and Drawbacks Explained
This article explains Spring's five bean scopes, focusing on the differences between singleton and prototype beans, their performance advantages, thread-safety concerns, and why Spring chooses singleton as the default scope.
Difference Between Singleton and Prototype Beans
If a bean is declared as a singleton, Spring creates only one instance in the container and reuses it for all subsequent requests, storing it in a map. For prototype beans, a new instance is created for each request without caching.
1. Diagram Analysis
2. Source Code Analysis
When generating a bean, Spring first determines whether it is singleton or prototype.
If it is a singleton, Spring attempts to retrieve it from the cache; if not found, it creates a new instance.
Conclusion
Singleton beans are created only once and then reused, reducing object creation overhead.
Prototype beans are created anew for each request.
Advantages of Singleton Beans
Because they are not created for each request, singleton beans offer several performance benefits:
1. Reduced Instance Creation Overhead
Creating instances involves reflection or CGLIB, both of which are performance-intensive, and memory allocation algorithms add further cost.
2. Reduced JVM Garbage Collection
Fewer bean instances mean fewer objects for the garbage collector to reclaim.
3. Faster Bean Retrieval
After the initial creation, beans are fetched from the cache, making access very fast.
https://juejin.im/post/5ca42bfa6fb9a05e17799e07
Disadvantages of Singleton Beans
A major drawback is the lack of thread safety for stateful beans; since all requests share the same instance, concurrent access can cause issues, unlike prototype beans which are isolated per request.
Summary
Why Does Spring Default Beans to Singleton?
To improve performance by reducing instance creation, minimizing garbage collection, and enabling fast cache-based retrieval.
Fewer instances created.
Less garbage collection.
Quick cache access.
What Are the Drawbacks?
Stateful singleton beans can be thread-unsafe in concurrent environments.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
