[英]PlayFramework Scala dependency Injection Javax
我是Scala和PlayFramework的新手,正在尝试弄清如何进行依赖注入。 我基本上想要一个将成为特征的文件,并将其注入控制器。 我的问题是我的Controller类没有看到我的Trait,这是我的代码
个人资料特质
package traitss
import play.api.mvc._
trait ProfileTrait extends Controller {
def Addone()
}
然后我尝试将其注入控制器
import java.nio.file.{Files, Paths}
import traitss.ProfileTrait_
import play.api.mvc.{Action, Controller}
import javax.inject._
class Profiles @Inject() (profileTrait: ProfileTrait) extends Controller
{
}
但是我的控制器没有看到它,我尝试按照此处的示例https://www.playframework.com/documentation/2.5.x/ScalaDependencyInjection进行操作 。 我正在使用播放框架2.50版
您不能直接注入特征。 您需要指定需要注入的特征的实现。
有两种方法可以指定要注入的特征的实现:
使用@ImplementedBy批注。 这是一个简单的例子:
package traitss
import play.api.mvc._
import com.google.inject.ImplementedBy
@ImplementedBy(classOf[ProfileTraitImpl])
trait ProfileTrait extends Controller {
def Addone()
}
class ProfileTraitImpl extends ProfileTrait {
// your implementation goes here
}
使用程序绑定
package traitss
import play.api.mvc._
import com.google.inject.ImplementedBy
@ImplementedBy(classOf[ProfileTraitImpl])
trait ProfileTrait extends Controller {
def Addone()
}
ProfileTraitImpl:
package traitss.impl
class ProfileTraitImpl extends ProfileTrait {
// your implementation goes here
}
创建一个模块,您可以在其中将实现与特征绑定
import com.google.inject.AbstractModule
class Module extends AbstractModule {
def configure() = {
bind(classOf[ProfileTrait])
.to(classOf[ProfileTraitImpl])
}
}
使用模块方法,您可以获得启用或禁用绑定的其他好处。 例如,在application.conf
文件中,可以使用play.modules.enabled += module
或 play.modules.disabled += module
启用/禁用play.modules.disabled += module
您不能注入特征,而必须注入实现该特征的对象。
为了使依赖项注入起作用,您必须告诉框架(后台使用Guice玩游戏)如何解决要注入的依赖项。 有很多方法可以执行此操作,具体取决于您的情况,有关更多详细信息 ,请参阅Guice的文档 ,最简单的方法是在app
目录中创建Module.scala
(如果尚不存在),然后放入类似这个:
import com.google.inject.AbstractModule
class Module extends AbstractModule {
override def configure() = {
bind(classOf[ProfileTrait]).toInstance( ... )
}
}
在...
何处放置逻辑以创建要注入的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.