scala案例类中的Google Guice字段注入

时间:2016-07-28 15:53:41

标签: scala playframework dependency-injection guice

我正在使用Scala编写Play 2.5应用程序。我有以下代码:

@ImplementedBy(classOf[BarRepositoryImpl])
trait BarRepository {
  def bar = //some actions
}
class BarRepositoryImpl extends BarRepository

case class Foo( /*some fields*/) {
  @Inject private var barRepository: BarRepository = null 
  def foo1 = {
    val a = barRepository.bar //here barRepository is always null
    // some actions with 'a' and returning some result which depends on 'a'
  }
}

我也有一个控制器,我也注入了BarRepository,但是通过构造函数,一切都运行良好,而在类foo上的行a val = barRepository.bar我得到一个NullPointerException。有人可以帮助弄清楚问题是什么吗?是否禁止在案例类中使用注射?

2 个答案:

答案 0 :(得分:0)

我会假设您在类签名中注入了对象?

case class Foo @Inject()(barRepository:BarRepository, /* your fields */){
    /** some stuff **/
}

答案 1 :(得分:0)

如果您不想使用Guice注入的注释和字段污染您的案例类签名,那么只需添加对需要它的方法的隐式依赖:

case class Foo( /*some fields*/) {
  def bar1(someField: Int)(implicit barRepository: BarRepository) = {
    // some code that interacts with barRepository
  }  
} 

调用类必须将BarRepository作为隐式注入的参数。例如。一个Play控制器,如:

@Singleton
class HomeController @Inject()(cc: ControllerComponents)
(implicit barRepository: BarRepository) 
extends AbstractController(cc)  {
  def index() = Action { implicit request =>
    val foo = Foo("field")
    val bar = foo.bar1
    // ...
  }
}