[英]Difference between static controller and non static controller in play framework with Java
I was wondering if there was any significant advantage, or disadvantage, when using non-static controllers in a Java Play!Framework 2.2.x app. 在Java Play!Framework 2.2.x应用程序中使用非静态控制器时,我想知道是否有任何明显的优势或劣势。
I normally use the clasic static controllers that seem to be the default pattern for Play!. 我通常使用似乎是Play!的默认模式的clasic静态控制器。
But whenever I use Guice I obviously need to change that so that I can inject various services. 但每当我使用Guice时,我显然需要改变它,以便我可以注入各种服务。 For those wondering how this is done (you add an '@' in front of the function "path" in the routes file):
对于那些想知道如何完成的人(在路径文件中的函数“path”前面添加一个'@'):
GET /api/something/someofthat controllers.MyController.myStaticAction
GET /api/something/someother @controllers.MyController.myNonStaticAction
public class MyController extends Controller {
public static Result myStaticAction(){
return ok("This is not a method.");
}
public Result myNonStaticAction(){
return ok("This is not a static method.");
}
}
Apart from the obvious and well documented advantage of dependency injection using Guice, it would seem to me that purely non static controllers would help in implementing thread-safe code. 除了使用Guice进行依赖注入的明显且记录良好的优点外,在我看来,纯粹非静态控制器将有助于实现线程安全代码。 But I must say I am not sure of that.
但我必须说我不确定。 So my question is: Can someone point me to cases in which NON-static controllers are recommended?
所以我的问题是: 有人能指出我推荐使用非静态控制器的情况吗? And also cases where static controllers are called for?
还有需要静态控制器的情况?
Also does it have any effect on the "scala wrapping" that play framework do on the controller functions? 它对播放框架对控制器功能的“scala包装”有什么影响吗?
Thanks a lot. 非常感谢。
The dependency injection you mentioned is, to me, the reason why non-static controllers should always be used. 你提到的依赖注入对我来说应该总是使用非静态控制器的原因。 It makes your code way easier to test.
它使您的代码更容易测试。
It is true that non-static controllers can make it slightly easier to write thread-safe code. 确实,非静态控制器可以使编写线程安全的代码更容易一些。 If you want to put mutable (and not shared across instances) state directly in your controller (which I do not recommend) it helps, however, the controller is only one part of your application, if you have non thread-safe code somewhere else it won't save you.
如果你想在控制器中直接放置mutable(而不是跨实例共享)状态(我不建议这样做),但是,如果你的其他地方有非线程安全的代码,那么控制器只是你应用程序的一部分。它不会救你。
Can't think of any reason why you would want to use static controllers. 想不出任何你想要使用静态控制器的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.