【发布时间】:2018-11-24 12:32:19
【问题描述】:
我正在使用 playframework 2.4 这是我的代码
trait UserRepositoryTrait {
val userRepo:UserRepository
val sessionRepo:SessionRepository
}
class UserRepositoryImpl extends UserRepositoryTrait {
@Inject @Named("userRepo")val userRepo:UserRepository= null
@Inject @Named("sessionRepo") val sessionRepo:SessionRepository = null
}
这里是模块类
class UserDependencyModule extends AbstractModule {
@Override
protected def configure() {
bind(classOf[UserRepository]).annotatedWith(Names.named("userRepo")).toInstance(new UserRepo)
bind(classOf[SessionRepository]).annotatedWith(Names.named("sessionRepo")).toInstance(new SessionRepo)
bind(classOf[UserRepositoryTrait]).to(classOf[UserRepositoryImpl])
}
}
在 application.conf 中
play.modules.enabled += "models.guice.UserDependencyModule"
如果我在控制器中注入这个特征,一切正常,但我想把这个特征注入到一个类中,这里是代码
class StatusChange @Inject() (userRepository:UserRepositoryTrait) {
}
我需要在Service.scala 类中致电StatusChange.scala
我如何实例化StatusChange.scala 对象
class ArtworkService() {
val status= new StatusChange(//what should i add here?)
}
我确实阅读了有关提供程序的信息,但我无法理解如何在我的场景中使用它?请指导我
更新 如果我这样做会是正确的吗?
class ArtworkService @inject (userRepository: UserRepositoryTrait) {
val status= new StatusChange(userRepository)
}
在控制器中
class MyController @inject (userRepository: UserRepositoryTrait)
{
val artworkService = new ArtworkService(userRepository)
}
【问题讨论】:
-
您的 ArtworkService 还需要注入 UserRepositoryTrait。
-
那么我如何将 UserRepostiryTrait 参数传递给 ArtworkService 类问题仍然存在(该类只会改变)我需要知道如何传递这些需要 @injected 实例的参数
-
根本上的问题是:创建
ArtworkService的线程的堆栈跟踪的根是什么?换句话说,是什么让该代码运行?如果这是来自某个控制器的调用链,那么您可以在此过程中拥有相关的@Inject 链(反向,即每次注入将被调用的组件)。如果代码是通过其他方式运行的,它究竟是如何运行的? -
它由控制器运行,请再次查看问题,我已对其进行了编辑
-
@swaheed,目前还不清楚
class MyController @Inject() (artworkService : ArtworkService)的直接方法对您有什么问题
标签: java scala playframework guice playframework-2.4