Search This Blog

Loading...

Sunday, January 8, 2012

JEE6: Observer pattern/Event implementation

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