Scala Play Guice 使用注入器手动注入已将配置注入其构造函数的单例 class

Scala Play Guice using injector to manually inject a singleton class that has configuration injected into its constructor

使用 play 2.5 和 guice 我已经成功地将 applicationConfig 注入到一个单例中 class 并在其中引用一个配置变量,

trait TMongoFactory{
  val SERVER: String
  val PORT: Int
  val DATABASE: String
  val connection: MongoClient
  val collection: MongoDB
}

@Singleton
class MongoFactory @Inject()(val configuration: Configuration) extends TMongoFactory{
  val SERVER = "localhost"         
  val PORT = 27017
  val DATABASE = configuration.underlying.getString("connectionString")
  val connection = MongoClient(SERVER, PORT)  
  val collection = connection(DATABASE)
}


class MongoModule extends AbstractModule {
  def configure() = {
    bind(classOf[TMongoFactory]).to(classOf[MongoFactory])
  }
}    

然后我可以像这样将这个单例传递到存储库class

@Singleton
class MongoRemainingAllowanceRepository @Inject()(MongoFactory: TMongoFactory) extends RemainingAllowanceRepository{
  val context = MongoFactory.collection("remainingAllowance")
  def save(remainingAllowance: RemainingAllowance): Unit ={
    context.save(RemainingAllowance.convertToMongoObject(remainingAllowance))
  }

这一切都按预期正常工作,但问题是我需要在测试套件中调用此存储库,所以我不希望它必须接受任何参数(特别是注入的参数)。 所以我试着把它改成在体内使用注射器,就像这样

@Singleton
class MongoRemainingAllowanceRepository extends RemainingAllowanceRepository{
  val injector = Guice.createInjector(new MongoModule)
  val mongoFactory = injector.getInstance(classOf[TMongoFactory])

  val context = mongoFactory.collection("remainingAllowance")
  def save(remainingAllowance: RemainingAllowance): Unit ={
    context.save(RemainingAllowance.convertToMongoObject(remainingAllowance))
  } 

这感觉它应该可以工作并且编译正常,但是在测试或 运行 时它会抛出错误

Could not find a suitable constructor in play.api.Configuration. Classes
must have either one (and only one) constructor annotated with @Inject
or a zero-argument constructor that is not private. at
play.api.Configuration.class(Configuration.scala:173) while locating
play.api.Configuration

很抱歉 post 但我觉得我需要包括其中的大部分内容。 有谁知道为什么这种情况发生在喷油器上?我是否还需要手动绑定配置,现在我正在引用自定义模块?

感谢任何帮助 谢谢 杰克

创建 class 时,您可以自己传入配置。假设您需要键 apiKey 及其值...

val sampleConfig = Map("apiKey" ->"abcd1234")
val mongoFactory = new MongoFactory(Configuration.from(sampleConfig))