CDI 2.0

Since Java EE 8 and CDI 2.0, events cannot only be handled synchronously. As we have seen previously in this book, CDI natively supports handling events asynchronously. In fact, this was only possible before if the event observer method was a business method of an EJB, annotated with @Asynchronous.

In order to emit and handle asynchronous CDI events, the publisher side uses the fireAsync method. The observer method parameter is annotated with @ObservesAsync.

Another new event functionality the advent of CDI 2.0 included is the possibility to order event observers. Therefore, the @Priority annotation, which is well-known within the Java EE platform, is specified at the event observer method:

public void onCarCreated(@Observes @Priority(100) CarCreated event) {
    System.out.println("first: " + newCoffee);
}

public void alsoOnCarCreated(@Observes @Priority(200) CarCreated event) {
    System.out.println("second: " + newCoffee);
}

This approach guarantees that the event observers are called in the specified order, with lower priority numbers first. Developers should consider whether the situation violates loose coupling and the single point of responsibility principle, by needing to order the event handlers.

The biggest feature of CDI 2.0 was the integration outside of an enterprise container, providing the possibility to use CDI in Java SE applications. The idea is that Java SE applications can also use the features of a sophisticated dependency injection standard. This aims to increase the acceptance of CDI outside of the Java EE world.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.137.117