Emitting domain events

CDI provides an eventing feature for cases where business functionality needs to be decoupled even more. Beans can fire event objects, which act as payloads and which are handled in event observers. By emitting and handling CDI events, we decouple the main business logic from side aspects of handling the event. This idea particularly matches use cases, where the business domain already comprises the concept of events. By default, CDI events are handled in a synchronous way; interrupting the execution at the point where they are fired. CDI events can also be handled asynchronously or at specific points in the life cycle of the technical transaction.

The following code demonstrates how to define and fire CDI events as part of a business use case:

import javax.enterprise.event.Event;

@Stateless
public class CarManufacturer {

    @Inject
    CarFactory carFactory;

    @Inject
    Event<CarCreated> carCreated;

    public Car manufactureCar(Specification spec) {
        Car car = carFactory.createCar(spec);
        carCreated.fire(new CarCreated(spec));
        return car;
    }
}

The CarCreated event is immutable and contains information that is relevant to the domain event, such as the car specification. The event is handled in the CreatedCarListener class, which resides in the control package:

import javax.enterprise.event.Observes;

public class CreatedCarListener {

    public void onCarCreated(@Observes CarCreated event) {
        Specification spec = event.getSpecification();
        // handle event
    }
}

The listener is therefore decoupled from the main business logic. The CDI container will take care of connecting the event handling functionality and synchronously calling the onCarCreated() method.

The topic Flow of execution, shows how events can be fired and handled asynchronously or alternatively at specific points in the life cycle of the transaction.

CDI events are a way how to decouple the definition of domain events from handling them. The event handler logic can be changed or enhanced without touching the car manufacturer component.

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

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