Guice注入注释值 [英] Guice inject annotation value
问题描述
您好,我想将注释值注入参数.例如
Hello i want to inject annotation value to parameter. for example
@BindingAnnotation
@Target({ ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
int value() default 0;
}
public class A {
@Inject @MyAnnotation(30)
protected Integer a;
}
我如何在a
变量中注入30.
how i can inject 30 inside the a
variable.
非常感谢
推荐答案
Use bindConstant()
as
bindConstant().annotatedWith(MyAnnotation.class).to(30);
您可以在整数字段上加上@Inject and @MyAnnotation
注释.
You can just have @Inject and @MyAnnotation
annotated on your integer field.
注意:
如果您的MyAnnotation
批注中还有一个元素,例如stringValue()
,
Note:
In case your MyAnnotation
annotation has one more element say stringValue()
like,
@BindingAnnotation
@Target({ ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
int value() default 0;
String stringValue default "";
}
为该元素bindConstant().annotatedWith(MyAnnotation.class).to("someValue")
再添加一个绑定似乎在以下情况下有效,但我认为这不是正确的方法.
adding one more binding for that element bindConstant().annotatedWith(MyAnnotation.class).to("someValue")
seems to work in the following case, but I feel this is not the correct approach.
public class A {
@Inject
public A(@MyAnnotation Integer integer, @MyAnnotation String string) {
//Here integer will be 10 and string will be someValue
}
}
这篇关于Guice注入注释值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!