Simple Event in Java EE

Event is a pretty useful concept when coding a domain logic that need to trigger some side effect (sending Email, SMS etc). All these action is not really part of the transaction but required.

To use event in java EE, we need some parts.

  1. The event type itself.
  2. Event handler.
  3. And a component to trigger the event.

Event Type:

An event type is just a Qualifier annotation. CDI container will find the event handler by its Qualifier.

@Qualifier
@Qualifier@Target({ElementType.FIELD,ElementType.PARAMETER})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface NewComer { }

This is just a simple qualifier boilerplate code.

Then in the servlet:

//controller body omitted
@Inject
@NewComer
Event newComerBroker;

//in doPost when criteria met
newComerBroker.fire("somepayload");

Finally for the event handler:
public class NewComerHandler {
    public void handleNewComer(@Observes @NewComer String name){

//Send an welcome email or some interesting stuff

 } 

}

the handleNewComer method will trigger when a the @NewComer event is fire from anywhere of the application.

Advertisements