Java EE 7 SDK 

Samples Main Page

The Events CDI Sample Application

Contexts & Dependency Injection (JSR 299) defines a standards-based, type-safe Dependency Injection mechanism in the Java EE platform. The type-safety comes from the fact that no String-based identifiers are used to identify the dependencies and instead all the information is specified using the Java object model. The loose coupling is possible because the bean requesting injection need not be aware of the lifecycle, concrete implementation, threading model, and similar details of the injected bean. The CDI runtime automatically figures out the right bean in the right scope and context and then injects it correctly for the requestor.

CDI Events take loose coupling to the next level by following the Observer pattern. Event producers raise events that are consumed by observers. The event object carries state from producer to consumer. The producer can fire the events and observer can specify qualifiers to narrow the set of events received.

Description

This sample illustrates how stateless EJBs can produce events and how singleton EJB can consume them. As EJBs in Java EE are also POJOs they have all the characteristics of a CDI bean as well. The sample uses a PrintServlet to invoke a print page stateless EJB. The bean fires events based upon the number of pages. These events are then consumed by the PrintObserver bean and a statement is printed out.

The following code snippet shows how PrintProducer fires events:

@Inject Event<PrintEvent> printEvent;
@Inject @BindIt Event<PrintEvent> printAndBindEvent;

public void print(int pages) {
    PrintEvent event = new PrintEvent(pages);
    if (pages < 10)
        printEvent.fire(event);
    else
        printAndBindEvent.fire(event);
}

The following code snippet shows how PrintObserver consumes events:

public void onPrintAndBind(@Observes @BindIt PrintEvent event) {
    System.out.println("Printing and binding " + event.getPages() + " pages");
}

public void onPrint(@Observes @Default PrintEvent event) {
    System.out.println("Printing " + event.getPages() + " pages");
}

Building, Deploying, and Running the Application

Perform the following steps to build, deploy, and run the application:

  1. Set up your build environment and configure the application server with which the build system has to work by following the common build instructions.
  2. app_dir is the sample application base directory: samples_install_dir/javaee7/cdi/events.
  3. Change directory to app_dir.
  4. Build, deploy, and run the sample application using the run outcome.

    mvn clean verify cargo:run

  5. Use the clean outcome to undeploy the sample application and to remove the temporary directories such as build and dist.

    mvn clean

Troubleshooting

If you have problems when running the application, refer to the troubleshooting document.



Copyright © 1997-2013 Oracle and/or its affiliates. All rights reserved.