每个 Web 请求是否由 Play 控制器类的新实例处理,即控制器是否可以将状态存储在注入控制器构造函数的服务等字段中?(文档在哪里解释?)
Is each web request handled by a new instance of a Play controller class, i.e. can a controller store state in fields such as services injected into the controller constructor? (where in the documentation is it explained?)
据我所知,控制器默认是单例对象.这没有明确记录,但暗示控制器实例被重用.请参阅 Playframework 2.4 迁移指南:
注入的路由生成器也支持路由上的@运算符,但它的含义略有不同(因为所有内容都是注入的),如果您在控制器前面加上@,而不是直接注入该控制器,则为 JSR 330 Provider该控制器将被注入.例如,这可用于消除循环依赖问题,或者如果您希望每个请求都实例化一个新操作.
The injected routes generator also supports the @ operator on routes, but it has a slightly different meaning (since everything is injected), if you prefix a controller with @, instead of that controller being directly injected, a JSR 330 Provider for that controller will be injected. This can be used, for example, to eliminate circular dependency issues, or if you want a new action instantiated per request.
另外,请查看 James Roper 提出的这个推荐(播放核心提交者)关于控制器是否是单例的:
并非如此 - 如果使用 Guice,每次将控制器注入某些东西时,默认情况下都会创建一个新实例.也就是说,路由器是单例的,因此通过关联,它调用的控制器是单例的.但是,如果您在其他地方注入控制器,它将为该组件重新实例化.
Not really - if using Guice, each time the controller is injected into something, a new instance will be created by default. That said, the router is a singleton, and so by association, the controllers it invokes are singleton. But if you inject a controller somewhere else, it will be instantiated newly for that component.
这表明默认情况下是在响应请求时重用控制器实例,如果您希望每个请求都有一个新操作,则需要使用迁移指南中描述的语法.但是...由于我更倾向于证明和尝试事物而不是仅仅相信,因此我创建了一个简单的控制器来检查该陈述:
package controllers
import play.api._
import play.api.mvc._
class Application extends Controller {
def index = Action {
println(this)
Ok(views.html.index("Your new application is ready."))
}
}
对该操作执行多个请求会为所有发出的请求打印相同的对象identity.但是,如果我在路由上使用 @ 运算符,我会开始为每个请求获取不同的 identities.所以,是的,控制器默认是(某种)单例.
对于控制器是有状态实例还是具有静态方法的无状态控制器,Play 框架与早期版本相比是否发生了变化(如果有,是什么版本?)?
Has the Play framework changed since earlier versions (and if so, at what version?) regarding if controllers are stateful instances or stateless controllers with static methods?
默认情况下,Play 一直提倡无状态控制器,您可以在项目主页看到:
Play 基于轻量级、无状态、网络友好的架构.
Play is based on a lightweight, stateless, web-friendly architecture.
这并没有改变.因此,您不应使用控制器的字段/属性来保存随时间/请求而变化的数据.相反,只需使用控制器的字段/属性来保持对同样无状态的其他组件/服务的引用.
在哪里可以看到使用有状态控制器时框架如何将服务注入控制器实例的代码示例以及如何将服务注入静态控制器方法的示例?
Where can you see code examples about how the framework injects services into a controller instance when stateful controller is used and example of how to inject services into a static controller method?
关于代码示例,Lightbend 模板存储库 是不错的选择.以下是一些在控制器级别使用依赖注入的示例:
- https://github.com/adrianhurt/play-api-rest-seed
- https://github.com/knoldus/playing-reactive-mongo
- https://github.com/KyleU/boilerplay
不支持使用静态方法的依赖注入,这就是 Playframework Stills 提供 旧 apis 与静态方法一起使用.这里的经验法则是:在 DI 和静态方法之间进行选择.尝试同时使用这两种方法只会给您的应用程序带来复杂性.
这篇关于是否每个 Play 框架 Web 请求都使用新的依赖注入控制器实例来处理,但是静态控制器方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持前端之家!
本文链接:https://www.f2er.com/3175496.html