Java 控制器在 Spring MVC 中的生命周期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1481993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Controller's life-cycle in Spring MVC
提问by flybywire
What is the lifecycle of a Controller in Spring MVC?
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.
控制器什么时候创建,什么时候销毁?它是否在多个线程之间共享?是否可以通过多个请求同时使用。
采纳答案by duffymo
Here's a view of the lifecycle:
这是生命周期的视图:
http://www.flickr.com/photos/60896767@N00/89101625/sizes/l/
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.
是的,它们由线程/请求共享;你应该把它们写成线程安全的。他们应该是无国籍的。通常他们有一个对完成所有工作的 Spring 服务的引用。控制器处理 Web 层的绑定、验证和路由。
回答by duffymo
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.
Spring MVC 的所有控制器都是单例的。与其他普通的单例 bean 一样,控制器的实例将在 Web 应用程序上下文开始后创建并在它结束之前处理。
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.
即使您为控制器 bean 定义指定了其他范围(例如,原型),因为 spring 为控制器提供了某种缓存以提高性能,因此只会重复使用第一个获取的控制器实例。
回答by Mainguy
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.
控制器只是 bean,它们可以是单例或原型,这取决于您要尝试做什么。如果你想要有状态使用原型,默认情况下它们是单例的。
http://www.digizenstudio.com/blog/2006/10/09/spring-controllers-with-prototype-scope/
http://www.digizenstudio.com/blog/2006/10/09/spring-controllers-with-prototype-scope/