Guice注入注释值 [英] Guice inject annotation value

查看:77
本文介绍了Guice注入注释值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想将注释值注入参数.例如

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆