Java Enterprise edition jee6 Observer pattern/Event
implementation using CDI (JSR-299/JSR-330) and EJB3.1
In few steps you will create the pattern as the following.
1. You will have to define an event class first. It can be
any POJO you like:
public class HelloEvent {
private String message;
public HelloEvent(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
2. An event has to be fired by an injected
javax.enterprise.event.Event class. It can be injected into an EJB 3.1:
@Named("messenger")
@Stateless
public class HelloMessenger {
@Inject Event<HelloEvent> events;
public void hello(){
events.fire(new HelloEvent("from bean " + System.currentTimeMillis()));
}
}
3. The event can be consumed by another Session Bean /
managed bean. You only have to use the @Observes annotation:
@Stateless
public class HelloListener {
public void listenToHello(@Observes HelloEvent helloEvent){
System.out.println("HelloEvent: " + helloEvent);
}
}
4. You can access the EJB 3.1 directly - without any backing
beans. You only have to use the name (messenger) from the @Named annotation in
the JSF 2.0 page and bind the action to the method (hello()) name:
<h:body>
<h:form>
<h:commandButton value="Fire!" action="#{messenger.hello}"/>
</h:form>
<h:body>
The project (Jee6ObsorverEvents) was implemented in few minutes with NetBeans 7.1, tested with Glassfish v3.1.1
Hi Mohamed,
ReplyDeleteDo you know how to use (is it allowed to use?) the Event fireing from ejb? I want to send state changes events from an ejb sessionbean to notify the managedbean (the observer in the web tier) about state changes of a long processing task in the ejb tier. (JMS is very heavy weigth I don't need "messages", events seems enough, I am in the same JVM with no view LocalBean) The "@Inject @Any Event myEvent" can not initiate the myEvent value...
Thanks for your help!
dejo