Java Reference
In-Depth Information
LISTING 6‐23: (continued)
return "A message";
public String messageBFactory(){
return "Another message";
You use @Name to annotate the producer methods and their matching injection points, as shown in
Listing 6‐24.
LISTING 6‐24: Injecting using @Named annotations
public class EventServiceName {
private String messageA;
private String messageB;
public void startService(){
System.out.println("Start service call " + messageA);
System.out.println("Start service call " + messageB);
Although this appears simpler than creating your own annotation type, in complicated systems, it
may not be a wise or a type‐safe choice. The named annotation works with the String provided in
quotes and is far from being type safe. The compiler can't warn you of potential bugs.
Harness the Power of CDI
If your application has multiple implementations of an interface and you want to implement
a factory pattern to produce the required instances of these objects, you are going to have
a factory class with multiple methods annotated with the @Produces annotation. This will
become verbose and difi cult to maintain. Fortunately, Java EE provides a solution in the form
of the @Any annotation and the imaginative use of enum types, annotation literals, and the
Instance class.
Search WWH ::

Custom Search