0

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

Shay_t
  • 163
  • 1
  • 16
  • 1
    Possible duplicate of [Guice inject based on annotation value](https://stackoverflow.com/questions/28549549/guice-inject-based-on-annotation-value) – kutschkem Feb 27 '18 at 14:42

1 Answers1

2

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
    }
}
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
  • what happens when user use annotation to another field called `@Inject @MyAnnotation(20) protected Integer b; @Inject @MyAnnotation(2) protected Integer c;` – Shay_t Feb 28 '18 at 06:54
  • @Shay_t I don't get you. The bindings here *seems* to happen by type (as you can see from my second code, it has one String and one Integer) – Thiyagu Mar 07 '18 at 10:32
  • you are binding a specific value "bindConstant().annotatedWith(MyAnnotation.class).to("someValue") " i want to bind the annotation value, when using the annotation. "@MyAnnotation(stringValue="hello there i am the value that will be assign to the str variable") String str;" – Shay_t Mar 07 '18 at 11:38