【问题标题】:Inject a list of objects to play application context注入对象列表以播放应用程序上下文
【发布时间】:2018-01-01 21:40:43
【问题描述】:

在我的项目中,我有一堆动物对象,例如:

其中一些有依赖注入:

class Monkey @Inject() (wsClient: WSClient, configuration: Configuration) extends Animal {
    ...
}

有些不是:

class Giraffe extends Animal {
    ...
}

在我的AnimalsService 类中,我需要一个所有动物对象实例的列表,

目前我的服务正在获取人员列表作为依赖注入:

class AnimalsService @Inject() (animals: List[Animal]) {
    // here I can use animals as my desire
}

然后我有一个绑定类来绑定它:

class Bindings extends AbstractModule {
  override def configure(): Unit = {
    bind(classOf[AnimalsService]).toProvider(classOf[AnimalServiceProvider])
  }
}

object Bindings {
  class AnimalServiceProvider @Inject () (giraffe: Giraffe, monkey: Monkey ...) extends Provider[AnimalsService] {
    override def get: AnimalsService = {
      new AnimalsService(List(giraffe,monkey...))
    }
  }
}

这很好用,但我更希望在应用加载时以某种方式将列表添加到我的应用程序上下文中,所以我不需要这样做......

这个当前的解决方案也意味着我需要在每次需要新动物时向AnimalServiceProvider 构造函数和这里添加新的动物AnimalsService(List(giraffe,monkey...)),这将不断发生......

处理这种情况的最佳方法是什么?

我想可能使用@Named guice 注释,但不确定它是否正确或如何以这种方式命名对象列表...

【问题讨论】:

    标签: scala playframework playframework-2.0 guice playframework-2.2


    【解决方案1】:

    我会做一个具有列表和添加定义的方法的 Singleton bean

    class AnimalsService @Inject() () {
        val animals: List[Animal]
        def addAnimal(animal: Animal) {
            ....
        }
        // here I can use animals as my desire
    }
    

    然后在每个需要动物的模块中都需要一个带有Eager bindings的额外单例

    class MonkeyConfigurator @Inject() (animalsService: AnimalsService) extends Animal {
        animalsService.add(this) //Or anything
        // here I can use animals as my desire
    }
    

    【讨论】:

    • 只是一个快速的想法,有一些细节缺失,我回家后尝试补充。
    猜你喜欢
    • 1970-01-01
    • 2017-12-17
    • 2015-08-21
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多