Java Reference
In-Depth Information
When you run and invoke the
startService
method, the string value in the producer method
is injected into the
message
member of
EventService
and printed to the console. This is the
simplest possible implementation of the factory pattern in Java EE. However, it raises one
important question: How does the Context Dependency Injection (CDI) container know that
it must inject the string produced by the
getMessage
method into the
message
member of
EventService
?
The answer: The CDI container relies on types to determine where to inject the produced type. In
this example, the produced type is a string, as is the injected type. So it matches the produced type
with the inject type and injects it.
You m ight argue that in a real system, you need to produce and inject different instances of the same
object type. How does the CDI container know where to inject each produced type? It does this by
using an annotation coni guration called a
qualii er
.
r
In real‐world projects, you probably want to return different object types instead of a simple string
so that you can create different objects by type.
LISTING 6‐12:
MessageA bean
package com.devchronicles.factory;
@Alternative
public class
MessageA
{
private String message;
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message = message;
}
}
LISTING 6‐13:
MessageB bean
package com.devchronicles.factory;
@Alternative
public class
MessageB
{
private String message;
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message = message;
}
}