Java Reference
In-Depth Information
The container injects an
Event
object of type
String
into the
event
instance variable of the
EventService
class. This forms part of the message when the
to fire String
object is i red. This
instance variable
Message
object is a String which may be produced by a factory. (See Chapter 6,
“Factory Pattern,” for more information about the factory design pattern injected to the EventService
class.) To make this example work without creating a factory even simpler, you can just dei ne any
String
constant to the variable called message and remove the
@Inject
annotation as follows.
private String message = "produced message";
Now the observable part is completed, so it is time to create an observer that listens for your
String
events. The addition of the
@Observes
annotation to the method signature marks the method as an
observer of events of the type it precedes. In this case, the
@Observes
annotation precedes the type
String
and thus listens for events of that type. The
@Observes
annotation followed by an object
type does the magic and lets the annotated method observe the i red event of the given type.
In Listing 11‐5, the
@Observes
annotation has been added to the
serviceTrace
method signature,
which marks the method as an observer for
String
events. When an event of type
String
occurs, the
serviceTrace
method receives the object that the event produced via its parameter.
serviceTrace
can then manipulate the
String
object as it wants. In this case, it prints the message
to the console.
LISTING 11‐5:
The observer bean
package com.devchronicles.observer;
import javax.ejb.Stateless;
import javax.enterprise.event.Observes;
@Stateless
public class TraceObserver {
public void serviceTrace(@Observes String message){
System.out.println("Service message: " + message);
}
}
If you run the server and invoke the
start service
method, you will realize how magically a
string will be injected to the
EventService
class, and then a
String
event is i red “where it will be
coughed (observed)” by the
serviceTrace
method of the
TraceObserver
class, and a message is
printed to the console. Surprisingly, this is all that you need to implement the observer pattern in
Java EE without further coni guration.
Although in real‐world scenarios you probably wouldn't be i ring and observing plain strings but
rather your own objects that would be observed by their type, it is still quite easy to differentiate
between the same object types of objects and set up different observers to listen for them.
You are now going to look at an example in which you use
Qualii ers
to disambiguate
String
objects. You have seen how this can be effective when implementing a factory pattern that produces
different implementations of the same type of object.