【问题标题】:Google Guice field injection in scala case classscala案例类中的Google Guice字段注入
【发布时间】:2016-12-03 03:14:19
【问题描述】:

我正在使用 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 类中的 val a = barRepository.bar 行中,我得到了 NullPointerException。有人可以帮助找出问题所在吗?案例类中是否禁止使用注入?

【问题讨论】:

    标签: scala playframework dependency-injection guice


    【解决方案1】:

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

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

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

    @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
        // ...
      }
    }
    

    【讨论】:

      【解决方案2】:

      我会假设您将对象注入到您的类签名中?

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

      【讨论】:

      • 我不能这样做,因为类 Foo 代表了一些业务逻辑的实体,并且在不同的地方被大量使用。此外,看起来问题不在于注入方法,我尝试将 BarRepository 作为字段注入控制器中,而不是使用构造函数,并且效果很好。我还尝试将控制器作为案例类,它仍然运行良好。
      • play框架的注入遇到了一些问题,但是当发现错误时,play的消息很不准确。您是否有来自 NullPointerException 的 StackTrace,可以添加到您的问题中?
      • 我想我找到了问题所在。我手动创建类 Foo 的实例,使用 operator new 和 Guice 不能以这种方式工作。要绑定 BarRepository Foo 实例应该由 Guice 以及 BarRepository 创建。
      • 好的,那么对不起。我问自己你是如何“创建”实例的,我想问你这个问题。但是由于我对 Guice 和 Play 以及它在控制器中工作的信息缺乏了解,我认为它应该按照您在问题中显示的方式工作。在我看来,Play-Framework/Guice 问题很难在一个简单的帖子中解决。但是感谢您告诉解决方案!
      猜你喜欢
      • 2016-09-04
      • 2016-09-07
      • 2014-12-17
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      相关资源
      最近更新 更多