简体   繁体   English

Guice 如何注入类型安全配置?

[英]How does Guice inject typesafe config?

Recently I am reading some scala code which uses Guice to inject the Typesafe Config.. It seems kind of magic to me how this works.. My question is, how to interpret this code?最近我正在阅读一些使用 Guice 注入类型安全配置的 Scala 代码..这对我来说是如何工作的似乎有点神奇..我的问题是,如何解释这段代码? Does Guice inject all those configuration values read in sbt-assembly into typesafe config automatically? Guice 是否会将 sbt-assembly 中读取的所有配置值自动注入类型安全配置?

Scala code:斯卡拉代码:

class FooImpl @Inject() (
  config: Config
) extends Foo {

  private val myConfig = "section.foo"

  override val batchSize = config.getInt(s"$myConfig.batchSize")

  .....
}

In Setting.scala在设置.scala

object Settings {
    ...
    assemblyMergeStrategy in assembly := {
      case "prod.conf" => MergeStrategy.concat
      case x =>
        val oldStrategy = (assemblyMergeStrategy in assembly).value
        oldStrategy(x)
    }
  ...

In prod.conf在 prod.conf

section {

  foo {
    batchSize = 10000
...

I think you're mixing three different mechanisms here :)我认为你在这里混合了三种不同的机制:)

  1. @Inject is indeed Guice, and it's a final step in the process. @Inject 确实是 Guice,这是该过程的最后一步。 Simply put, Guice has a "dependency injection container" that knows where to look for instances of certain types.简单地说,Guice 有一个“依赖注入容器”,它知道去哪里寻找特定类型的实例。 One of the types it knows of is the Config .它知道的类型之一是Config How it knows this depends on the framework you're using (or how you instantiate your Guice container if you're not using it);如何知道这取决于您使用的框架(或者如果您不使用它,您如何实例化您的 Guice 容器);

  2. Typesafe config has rules on where to look for configuration.类型安全配置有关于在哪里寻找配置的规则。 Readme sums it pretty good, but in short - it finds application.conf in resources folder (or, actually, anywhere on the classpath), and then imports all the other files that application.conf explicitly imports (using import other_conf.conf ).自述文件总结得很好,但简而言之 - 它在资源文件夹(或者,实际上,在类路径上的任何位置)中找到 application.conf,然后导入application.conf显式导入的所有其他文件(使用import other_conf.conf )。 I'm assuming in your case there's import prod.conf somewhere in the application.conf我在你的情况下,假设有import prod.conf在某处application.conf

  3. Assembly - just puts all the resources from all the dependencies into one giant resource folder - specifying rules on what to do if there are multiple files wit hthe same name.程序集 - 只是将所有依赖项中的所有资源放入一个巨大的资源文件夹中 - 指定在存在多个同名文件时要做什么的规则。 In your case, it tells it to just concatenate them.在你的情况下,它告诉它只是连接它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM