Adam Bien's Weblog
Java EE 6 Observer Pattern / Events With CDI (JSR-299/JSR-330) and EJB 3.1
1. You will have to define an event class first. It can be any POJO you like:
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>
[...]
The project (CDIEJB3Events) was implemented in few minutes with NetBeans 6.8, tested with Glassfish v3 and pushed into: http://kenai.com/projects/javaee-patterns/. The entire WAR (JSF 2.0 , EJB 3.1, CDI) is 8 kB small. The initial deployment took (897 ms):
INFO: Initializing Mojarra 2.0.2 (FCS b10) for context '/CDIEJB3Events'
INFO: Loading application CDIEJB3Events at /CDIEJB3Events
INFO: CDIEJB3Events was successfully deployed in 897 milliseconds.
Posted at 09:00AM Dec 17, 2009 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[3]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices


If I may notice, this is similar to what Spring supports (javadoc states since 1.1.1) via ApplicationEventPublisher.publishEvent ( http://bit.ly/5PSYS5 ) implemented by (Web)ApplicationContext so bean had to implement ApplicationContextAware, event had and seems still with 3.0.0.RELEASE has to extend ApplicationEvent, and @Observes seems cleaner than implementing ApplicationListener<E extends ApplicationEvent> too, so + for @Inject.
Gesendet von Stevo Slavic am December 17, 2009 at 03:26 PM CET #
@Stevo,
perfect - then Spring apps are easier portable to Java EE 6 and vice versa! See: http://www.adam-bien.com/roller/abien/entry/8_reasons_why_java_ee point 9.
Would be the Spring solution easier / leaner than Java EE 6?
regards && thanks!,
adam
Gesendet von Adam Bien am December 17, 2009 at 04:28 PM CET #
I have to create a bean.xml file on WEB-INF, in order to index.xhtml could resolve #{mesenger.hello}
¿is it an automatic way to have these file created? or ¿have it to be always manually created?
Greetings
Gesendet von nestorgm am February 05, 2010 at 12:05 AM CET #