当前位置: 首页 > 知识库问答 >
问题:

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

孟哲
2023-03-14

我正在使用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,但是通过构造函数,在 val a barRepository.bar= 的类 Foo 中,我得到一个 NullPointerException,一切都运行良好。有人可以帮助找出问题所在吗?是否禁止在案例类中使用注射?

共有2个答案

益炜
2023-03-14

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

case class Foo @Inject()(barRepository:BarRepository, /* your fields */){
    /** some stuff **/
}
滕无尘
2023-03-14

如果您不想让Guice注入的注释和字段污染您的case类签名,那么只需在需要它的方法上添加一个隐式依赖即可:

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

调用类必须将BarRepostory作为隐式注入的参数。例如。像这样的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
    // ...
  }
}
 类似资料:
  • 如何只在pos时返回case类

  • 问题内容: 您将如何在PySpark中使用和/或实现等效的案例类? 问题答案: 正如Alex Hall[所提到的,命名产品类型的真实等效项是。 与在其他答案中建议的不同,它具有许多有用的属性: 具有明确定义的形状,可以可靠地用于结构模式匹配: FooBar = namedtuple(“FooBar”, [“foo”, “bar”]) foobar = FooBar(42, -42) foo, ba

  • 大家好,我在SCALA上创建了以下案例类: 然后,如您所见,BGP包含Term并扩展到模式,Val包含值并扩展到Term,U、L、B包含字符串并扩展到Value,在我的函数中,我想访问包含U或L或B大小写类的字符串,变量valor=Val(y). value包含一个U类,例如,但当我编写valor时。XXXX没有给我显示名称选项。最大的问题是如何从U访问字符串名称?

  • 本文向大家介绍Scala案例分类和不可变性,包括了Scala案例分类和不可变性的使用技巧和注意事项,需要的朋友参考一下 示例 Scala编译器默认在参数列表中为每个参数加上前缀val。这意味着,默认情况下,案例类是不可变的。每个参数都具有一个访问器方法,但是没有可变器方法。例如: 在案例类中将参数声明为var会覆盖默认行为,并使案例类可变: 案例类为“可变”的另一个实例是案例类中的值是可变的: 请

  • 问题内容: 是否有关于何时使用案例类(或案例对象)与扩展Scala中的枚举的最佳实践指南? 他们似乎提供了一些相同的好处。 问题答案: 最大的不同是Enumerations支持从某些nameString实例化它们。例如: 然后,您可以执行以下操作: 当希望保留枚举(例如,到数据库)或根据文件中的数据创建枚举时,此功能很有用。但是,我发现总体上来说,枚举在Scala中有点笨拙,并且具有附加组件的尴尬

  • 我看到过一些关于的博客,这些博客似乎可以很好地为类添加行为。 但是,如果我有一个并且我要怎么办?作为一个case类,我不能扩展它(不推荐/强烈不鼓励从case类继承)。这些皮条客模式是否允许我将数据添加到case类中?