Shay_t
Shay_t

Reputation: 163

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

how i can inject 30 inside the a variable.

thank you very much

Upvotes: 0

Views: 479

Answers (1)

Thiyagu
Thiyagu

Reputation: 17880

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

Upvotes: 2

Related Questions