Reputation: 1382
I'm new to Context Dependency Injections in Java EE (I'm on EE 6), and I would like to please ask about something I ran into:
Let's say you declare this annotation:
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Qualifier
public @interface MaxPassengers {}
In a different class I say that the getMaxPassengers method produces the value to be injected when the @MaxPassengers annotation is used:
public class AirplaneInformation implements Serializable {
@Produces @MaxPassengers Integer getMaxPassengers() {
return 250;
}
}
In yet a third class, I inject the @MaxPassengers into a variable:
@MaxPassengers
@Inject
private Integer maxPassengers;
All this work great, but here's the twist:
What if I want change the signature of @Produces @MaxPassengers Integer getMaxPassengers() to @Produces @MaxPassengers Integer getMaxPassengers(String planeType)
And return the a dynamic value of maxPassengers based on the planeType.
I'm wondering if this can be done, and if so, how do I change the following annotation
@MaxPassengers
@Inject
private Integer maxPassengers;
to also supply the planeType argument.
Thank you for your help, -Daniel
Upvotes: 0
Views: 68
Reputation: 11723
The way this is done is to add the planeType
to the qualifier as @NonBinding
. You would then pass in an InjectionPoint
object to your method and look up the MaxPassengers
this way: injectionPoint.getAnnotated().getAnnotation(MaxPassengers.class);
If you want to pull this up at runtime, you would use an Instance
object an an AnnotationLiteral
of your MaxPassengers
, something like this:
@Inject @Any
private Instance<Integer> integerInstance;
...
integerInstance.select(new MaxPassengersLiteral("foo")).get();
Upvotes: 1