为什么在play 2.5中使用单例控制器? [英] Why use singleton controllers in play 2.5?

查看:94
本文介绍了为什么在play 2.5中使用单例控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才刚刚起步,我认为我不太了解.据我了解,路由器创建后,所有控制器都被创建为依赖项.然后它们继续存在,直到路由器在应用程序终止时死掉为止.如果是这种情况,则将它们声明为单例似乎是多余的.

I'm just starting out and I dont think i understand it very well. From what I understand all controllers are created as dependencies the moment the router is created. They then live on until the router dies when the application terminates. If this is the case declaring them as singletons seem redundant.

推荐答案

要摆脱全局状态(这与无状态设计的想法背道而驰),Play引入了DI(我在v2.4左右)和v2.5中引入现在默认情况下使用注入的路由器. Google Guice是Play打包的默认DI框架(您可以使用其他框架,但Guice是默认框架).

To get rid of global state (which goes against the idea of a stateless design) Play introduced DI (I think around v2.4) and in v2.5 it now uses an injected router by default. Google Guice is the default DI framework packaged by Play (you can use others but Guice is the default).

现在(一般而言),Guice认为创建Controller的新实例比使用单例更快,并且线程安全性更高-请参阅

Now (in general) Guice takes the view that creating new instances of a Controller is faster, and more thread safe than using a singleton - see the Guice docs for more.

如果您有必要将控制器实例限制为只有1,然后您可以将其标记为单例,但必须将其标记为 Thread-安全,因为它将在线程之间共享.

If you have a need to restrict instances of a controller to only 1 then you can mark it a singleton BUT you have to make it Thread-safe since it will then be shared between threads.

我认为Activator模板可以在其周围添加更多文档,以解释为什么似乎不需要时它们似乎会生成@Singleton控制器的原因,因为这很令人困惑.例如,HomeController(在Play-Scala种子中)在没有任何理由的情况下被混淆地声明为@Singleton.

I think the Activator templates could do with a bit more documentation around them to explain why they seem to generate @Singleton controllers when they do not seem to be needed since it is confusing. HomeController (in the Play-Scala seed) for example is confusingly declared @Singleton when it exhibits no case for it.

通常,最好不要使用@Singleton,除非您对不变性和线程安全性有充分的了解.如果您认为自己有Singleton的用例,则只需确保保护任何共享状态即可.

In general, it is probably best to not use @Singleton unless you have a fair understanding of immutability and thread-safety. If you think you have a use case for Singleton though just make sure you are protecting any shared state.

简而言之,不要使用@Singleton.

这篇关于为什么在play 2.5中使用单例控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆