本文介绍了Play Framework的ScalaRouting中的依赖项注入路由器和静态路由器之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Play Framework的ScalaRouting中,依赖项注入路由器和静态路由器之间有什么区别?

What is the difference between the dependency injected router and the static router in ScalaRouting of Play Framework?

当使用Play Seed Activator模板创建新的Play应用程序时,Play框架文档将指导使用依赖项注入路由器.

Play framework documentation directs dependency injected router is used when a new Play application is created by using the Play seed Activator templates.

但是我仍然对这两个路由器感到困惑.

But I am still confused about both routers.

如果有人知道,请教我.

If anyone knows, please teach me.

推荐答案

简而言之

动态路由器可提供对控制器实例化的更多控制.它使您可以使用依赖项注入框架来管理依赖项,并使控制器测试变得更加容易.静态路由器可以作为原型的首选,因为它是默认设置.对于资产来说,这也是显而易见的选择,因为它们也是静态的.

The dynamic router gives more control over controller instantiation. It allows you to managed dependencies using a dependency injection framework and makes controller testing a lot easier. The static router can be preferred for prototyping as it's setup by default. It's also an obvious choice for the assets as they're also static.

扩展答案

这一切都始于静态路由器.在Play 2.0中,您只能将控制器创建为带有静态方法的类(在Java中)或作为对象(在Scala中).在设计MVC时,控制器是无状态的,因此您不需要此类的多个实例.但是,静态方法和对象的问题在于它们很难进行单元测试,尤其是模拟或存根依赖项.依赖注入也很痛苦.

It all started with the static router. In Play 2.0 you could create a controller only as a class with static methods (in Java) or as an object (in Scala). It was designed in mind that in MVC controllers are stateless and hence you don't need multiple instances of such class. However, the problem with static methods and objects was that they're hard to unit test, especially mocking or stubbing dependencies was the issue. Dependency injection was also quite painful.

感谢积极的批评,播放2.1引入了新机制处理此问题,该问题允许动态对象实例化.从这一点开始,您可以通过在路由文件中的类名称前放置@来在两种路由方法之间进行选择.

Thanks to positive criticism, Play 2.1 introduced new mechanism to handle this problem, which allowed dynamic object instantiation. From this point you're able to choose between both route methods by placing @ before a class name in the routes file.

在2.4之前,动态创建是通过所谓的Global对象中的getControllerInstance()方法完成的,但是此机制已在2.4 中删除,并由更复杂的依赖项注入方法代替.

Before 2.4 dynamic creation was done using a getControllerInstance() method in a so-called Global object, but this mechanism was removed in 2.4 and replaced by more sophisticated dependency injection approach.

保留静态路由器的主要目的是用于非常简单的用例,并且由于向后兼容,但是,对于较新的项目,我建议使用动态路由器,因为它没有其前身的缺点.

The static router is kept mostly for very simple use cases and because of backward compatibility, yet, for newer projects I would suggest going with the dynamic router as it's free of disadvantages of its predecessor.

这篇关于Play Framework的ScalaRouting中的依赖项注入路由器和静态路由器之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 03:05