Java EE 7 SDK |
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.
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"); }
Perform the following steps to build, deploy, and run the application:
app_dir
is the sample application base directory: samples_install_dir/javaee7/cdi/events
.app_dir.
run
outcome.
mvn clean verify cargo:run
clean
outcome to undeploy the sample application and to remove the temporary directories such as build
and dist
.
mvn clean
If you have problems when running the application, refer to the troubleshooting document.
Copyright © 1997-2013 Oracle and/or its affiliates. All rights reserved.