What values () do I see in the various CDI qualifiers in Java?
I see various references to values () in the @ qualifier definition
An interface can allow enumeration, but I don't understand the word values () I see in the two unrelated examples listed below
Can you explain to me what the word value () means?
@Qualifier @Retention(RUNTIME) @Target({FIELD,TYPE,METHOD}) public @interface NumberOfDigits { Digits value(); } public enum Digits { TWO,EIGHT,TEN,THIRTEEN }
package com.byteslounge.bean; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Qualifier; @Qualifier @Retention(RUNTIME) @Target({FIELD,METHOD}) public @interface MessageTransport { MessageTransportType value(); }
Solution
These are not interfaces These are annotations You can declare static information on comments and annotate it The code that examines the comments can then take advantage of this information
Comments declared as qualifier allow CDI to disambiguate between implementations of the same type
Consider the qualifier foo:
@Qualifier @Retention(RUNTIME) @Target({FIELD,METHOD}) public @interface Foo { int value(); }
Types annotated with foo:
@Foo(1) public class Bar implements Runnable { //...impl @Foo(2) public class Baz implements Runnable { //...impl
A CDI bean:
public class Bean { @Inject @Foo(1) Runnable a; @Inject @Foo(2) Runnable b; //...impl
Here, a will be resolved to an instance of bar and B will be resolved to an instance of Baz
Without qualifier comments, the CDI API cannot tell which runnable instance to inject All values must match exactly