Are Spring MVC Controllers Singletons?

JavaSpringSpring Mvc

Java Problem Overview


I have a query regarding Spring 3 MVC @Controllers. When a request comes in, does the container create a new instance of the controller for each request (Similar to an Action in Struts 2 - ThreadLocal ActionContext) or a single instance responds to all requests? By default are the controller beans singletons in a context?

What are the guidelines/ best practices for a Spring 3 MVC application? Are these settings configurable? Should those be configured? Does it change much if my environment is a clustered environment - I guess it should not as the jvm/containers would be different- but some authoritative suggestion would be welcome.

I have read Spring documentation but probably I missed it. Any 'this is how we implemented kind of' answers/ pointers/ links would be helpful Thanks.

Java Solutions


Solution 1 - Java

Spring controllers are singletons (there is just one instance of each controller per web application) just like servlets. Typically there is no point in changing this behaviour (if it's even possible). See https://stackoverflow.com/questions/11485486 for common pitfalls, also applying to controllers.

If your application is clustered do as much as you can to avoid state. State in controllers will require synchronization to avoid threading issues. Also you'll probably replicate that state across servers - very expensive and troublesome.

Solution 2 - Java

By default, Spring beans are singletons. Spring suggests to use singletons for stateless beans like controllers and DAOs, and prototype scope for stateful beans.

Solution 3 - Java

The Struts2 Actions are not singletons because they carry state. Struts2 leverages javabeans properties on the action itself to carry the incoming request data and expose it to the various layers of the framework.

Spring, on the other hand, uses a model object that is handed to the controller. The controller itself doesn't hold state, so a singleton makes sense.

Solution 4 - Java

Controller are singletons thus can avoid creating a lot of instances by keyword new if the webapp process a lot of requests at the same time.Using controller singleton could also relief the burden of JVM by decreasing young GC.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAtulView Question on Stackoverflow
Solution 1 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - JavaRamsView Answer on Stackoverflow
Solution 3 - JavachadView Answer on Stackoverflow
Solution 4 - JavaMrBoyView Answer on Stackoverflow