flybywire
flybywire

Reputation: 273892

Controller's life-cycle in Spring MVC

What is the lifecycle of a Controller in Spring MVC?

When is the controller created, when destroyed? Is it shared among multiple threads? Can it be in use simultaneously by more than one request.

Upvotes: 41

Views: 33623

Answers (3)

Mainguy
Mainguy

Reputation: 1669

Controllers are just beans, they can be singleton or prototype, it depends on what you are trying to do. If you want statefulness use prototype, by default they are singleton.

http://www.digizenstudio.com/blog/2006/10/09/spring-controllers-with-prototype-scope/

Upvotes: 15

user179633
user179633

Reputation:

All controllers of Spring MVC are singleton. As other normal singleton beans, instance of controllers will be created after start of web application context and disposed before end of it.

Even you specify other scope (for example, prototype) for controller bean definition, because spring has some kind of cache for controllers for performance, only the first acquired instance of controller will be used repeatedly.

Upvotes: 10

duffymo
duffymo

Reputation: 308948

Here's a view of the lifecycle:

http://www.flickr.com/photos/60896767@N00/89101625/sizes/l/

Yes, they're shared by threads/requests; you should write them to be thread-safe. They should be stateless. Usually they have a reference to a Spring service that does all the work. Controllers handle binding, validation, and routing for the web tier.

Upvotes: 29

Related Questions