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

时间:2017-07-14 18:06:56

标签: scala guice

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

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

请注意我正在寻找使用通用特征/类的解决方案。

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

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

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

1 个答案:

答案 0 :(得分:1)

你会像在Java中那样在Scala中完成它。首先,定义注释:

/**
 * 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] {}

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

此外,如果您将Guice与Scala一起使用,请考虑使用scala-guice;除此之外,它允许你省略这些笨重的classOf s。

相关问题