Scala Play Guice使用注入器手动注入一个单例类,该类具有注入其构造函数的配置

时间:2016-09-09 20:46:45

标签: scala playframework dependency-injection guice

使用play 2.5和guice我已成功将applicationConfig注入单例类并引用其中的config变量,

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])
  }
}    

然后我可以将这个单例传递给像这样的存储库类

@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

长篇大论道歉,但我觉得我需要包括大部分内容。 有谁知道为什么这会在注射器上发生?我是否需要手动绑定配置现在我引用自定义模块?

任何帮助表示赞赏 谢谢 千斤顶

1 个答案:

答案 0 :(得分:1)

创建课程时,您可以自行传递配置。假设您需要键apiKey及其值...

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