Scala Guice 如何将配置参数作为字符串注入?

Scala Guice how to inject configuration parameter as string?

我在 Java 中找到了以下代码,解释了如何使用 guice 将配置参数作为带注释的字符串参数很好地注入。 https://github.com/google/guice/wiki/FrequentlyAskedQuestions

我想做同样的事情,但在 Scala 中。 你会怎么做?

请注意,我正在寻找使用通用 trait/class 的解决方案。

的东西
trait Foo[T <- SomeOtherType] {}
class FooImpl[T <- SomeOtherType](val url: String) extend Foo[T] {}

我调查了辅助注射,但无法解决我的问题。

任何帮助将不胜感激。 谢谢

您在 Scala 中的操作与在 Java 中的操作完全相同。首先定义一个注解:

/**
 * Annotates the URL of the foo server.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface FooServerAddress {}

注意这是Java代码;您不能在 Scala 中定义运行时注释。

然后你绑定一个用这个注释注释的常量:

bindConstant().annotatedWith(classOf[FooServerAddress])

最后,你注入它:

class FooImpl[T] @Inject() (@FooServerAddress val url: String) extends Foo[T] {}

目标的通用性 class 在这里并不重要。

此外,如果您将 Guice 与 Scala 结合使用,请考虑使用 scala-guice;除其他外,它还允许您省略这些笨重的 classOfs.