Guice inject annotation value

拥有回忆 提交于 2019-12-11 17:53:34

问题


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;
}

how i can inject 30 inside the a variable.

thank you very much


回答1:


Use bindConstant() as

bindConstant().annotatedWith(MyAnnotation.class).to(30);

You can just have @Inject and @MyAnnotation annotated on your integer field.


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 "";
}

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
    }
}


来源:https://stackoverflow.com/questions/49010954/guice-inject-annotation-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!