我在Java中找到以下代码,解释了如何使用guice将配置参数很好地注入为带注释的字符串参数。https://github.com/google/guice/wiki/FrequentlyAskedQuestions
除了scala,我想做同样的事情。你会怎么做?
并请注意,我正在寻找使用通用特征/类的解决方案。的东西
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] {}
目标类的泛型在这里并不重要。
另外,如果将Guice与Scala一起使用,请考虑使用scala-guice;其中,它可以让您忽略这些笨拙的classOf
s。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句