• Creating and Using Contexts and Dependency Injection (CDI) Events

    Events are an important part of the JavaBeans model. You have probably used events in Abstract Windowing Toolkit (AWT) and Swing applications by registering a listener on a component. When you click the component (like a button), an event is fired and handled by the registered listener.

    Contexts and Dependency Injection (CDI) was introduced with Java Platform, Enterprise Edition (Java EE) 6 as JSR-299. The Contexts part of CDI allows beans to share and participate in the life cycle of another bean, while the Dependency Injection part of CDI allows beans to get a reference to an instance of another bean simply by injecting it. CDI power is the ability to loosely-couple classes by removing the instantiation process and simultaneously enforcing strong-type checking. CDI provides an @Inject annotation to create a reference to another bean (avoiding the older context lookup process). CDI enforces typing by eliminating string-based lookup so that the compiler can detect errors. CDI works very well with integrated development environments (IDE's).

    The CDI event model allows beans to send events to one another without a compile-time dependency, and beans may create their own event payloads - a class that contains information pertinent to the event. Using CDI events, one bean can define the event, another can fire the event and a third can handle the event. And unlike with other event models, you can add listeners (observers) without registering them as listeners.

    Duration: 45 minutes

    Release Date: 14-JAN-2013

    Created by: Tom McGinn

Reviews (1)

  • 12.1 years ago
    emil.prager
    A pretty good introduction to CDI events, qualifiers and handlers (recommending some best practices for decoupling the event firing code from the "application" code). Only some minor remarks: - not necessary to add a no-arg constructor for the event class (not only because it would be added anyway by the compiler, but it's effectively not required); - when switching from the 1st variant (firing the event directly in our code) to the 2nd one (use an interceptor for that), it should be mentioned that also the injected event field: @Inject @Bid private Event<AuctionEvent> bidEvent; should be commented (or it would remain an orphan one); Also (but optional) maybe it would be useful to finish with a slightly more modified variant that would emphasize the usage of qualifiers for filtering the treatment of the events. E.g. with 2 types of events, an interceptor with something like: @Inject @Bid private Event<AuctionEvent> bidEvent; @Inject @GiveUp private Event<AuctionEvent> giveUpEvent;
    • emil.prager
      12.1 years ago
      PS: Unfortunately, the review text will be harder to read since the page displays it on a single line :-(
    • tom.mcginn
      12.1 years ago
      Thanks Emil! I appreciate the feedback and will look at making the changes you suggest.

Buttons