Java Reference
In-Depth Information
What would take many tens if not hundreds of lines of code to produce each instance, you
can accomplish in just four lines of code. You can achieve this by collecting all instances of a
particular interface implementation and selecting the one you want to use by using the @Any
annotation.
The @Any annotation instructs the container that all beans implementing the given interface should
be injected at that injection point. In the listing below the code private Instance<MessageType> ,
messages injects instances of all dependencies that implement the MessageType interface into the
member variable messages .
Once all dependencies have been injected, you need a way to distinguish between them and
select the one you want to use. This is where the use of annotation literals and enum types
comes into play. In the listings that follow, you dei ne an @Message qualii er and the enum
literals SHORT and LONG . These distinguish between the implementations of the MessageType
interface.
To select the dependency, compare it with the enum type of the qualii er of each implementation by
creating an AnnotationLiteral of the type you are searching for, retrieve it, and return it to the
client.
Now you'll see how this is implemented in code. You will use the example of a factory that produces
ShortMessage and LongMessage objects, each implementing the Message interface annotated as
either SHORT or LONG .
LISTING 6‐25: MessageType interface
public interface MessageType {
public String getMessage();
public void setMessage(String message);
}
LISTING 6‐26: ShortMessage implementation of message interface
@Message(Message.Type.SHORT)
@Dependent
public class ShortMessage implements MessageType {
private String message;
@Override
public String getMessage() {
return message;
}
@Override
public void setMessage(String message) {
this.message = message;
}
}
Search WWH ::




Custom Search