Backend Development 5 min read

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.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Understanding Singleton and Prototype Scope in Spring MVC Controllers

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.............静态属性:3

Result: 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.............静态属性:3

Result: 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.............静态属性:3

Result: 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
JavaControllersingletonPrototypescopeSpringMVC
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.