Java Reference
In-Depth Information
IMPLEMENTING THE FACTORY PATTERN IN JAVA EE
The factory pattern is not tricky to implement, as you have seen in the preceding examples.
Java EE offers a simple and elegant way to implement the factory pattern via annotations and
dependency injection. In the Java EE world, you use the @Produces annotation to create an object,
and you use @Inject to inject the created object (or resource) where it's required. The simplest
implementation in Java EE of the factory method follows in Listing 6‐10.
LISTING 6‐10: Simple implementation of the factory method using producer methods
package com.devchronicles.producer;
import javax.enterprise.inject.Produces;
public class EventProducer {
@Produces
public String getMessage(){
return "Hello World";
}
}
The getMessage method is annotated with @Produces and results in String objects containing
the text Hello World . Although the type produced in this example is a string, you can produce
anything you need, including interfaces, classes, primitive data types, Java array types, and core
Java types.
To use the produced object, you need to inject the same type into the class where you are going to
use it, as demonstrated in Listing 6‐11.
LISTING 6‐11: Injecting a string created by the factory
package com.devchronicles.factory;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService {
@Inject
private String message;
public void startService(){
System.out.println("Start service call " + message);
}
}
 
Search WWH ::




Custom Search