Understanding Singleton and Prototype Scope in Spring MVC Controllers
This article explains how Spring MVC controller beans behave under singleton and prototype scopes, showing that normal instance fields are shared only in singleton beans while static fields are always shared, and recommends using @Scope("prototype") when defining controller attributes.
This article demonstrates the behavior of Spring MVC controller beans when they are singleton or prototype scoped, using simple code examples and output screenshots.
First test: the class is defined as prototype (multiple instances) with a normal instance field and a static field.
普通属性:0.............静态属性:0
普通属性:0.............静态属性:1
普通属性:0.............静态属性:2
普通属性:0.............静态属性:3Result: for prototype beans the normal instance field is not shared, while the static field is shared across all instances.
Second test: the class is defined as singleton.
普通属性:0.............静态属性:0
普通属性:1.............静态属性:1
普通属性:2.............静态属性:2
普通属性:3.............静态属性:3Result: in singleton scope both the normal instance field and the static field are shared.
Third test: remove the @Scope annotation.
普通属性:0.............静态属性:0
普通属性:1.............静态属性:1
普通属性:2.............静态属性:2
普通属性:3.............静态属性:3Result: Spring MVC defaults to singleton scope for controllers.
Additional observations from other methods show that once a field is shared, subsequent method calls continue to use the shared value rather than resetting to the initial value.
Conclusion
Avoid defining fields inside controller classes; if you must keep state, annotate the controller with @Scope("prototype") to make it prototype scoped.
Historically, Struts used class-level fields which were shared (multi‑instance), leading to thread‑safety concerns, whereas Spring MVC is method‑oriented, receiving parameters via method arguments, and its default singleton design is safe as long as no mutable fields are defined.
Therefore, controllers without instance fields are safe under the default singleton scope, and this design improves performance and maintainability.
Open question: Is the default singleton controller thread‑safe? Feel free to comment with answers.
Source: blog.csdn.net/qq_27026603/article/details/67953879
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.