10.2.9.2. Fire and Observe Events

Example 10.15. Fire an event

This code shows an event being injected and used in a method.
public class AccountManager {
  @Inject Event<Withdrawal> event;
  
  public boolean transfer(Account a, Account b) {
    ...
    event.fire(new Withdrawal(a));
  }
}

Example 10.16. Fire an event with a qualifier

You can annotate your event injection with a qualifier, to make it more specific. For more information about qualifiers, see Section 10.2.3.2, “About Qualifiers”.
public class AccountManager {
  @Inject @Suspicious Event <Withdrawal> event;
  
  public boolean transfer(Account a, Account b) {
    ...
    event.fire(new Withdrawal(a));
  }
}

Example 10.17. Observe an event

To observe an event, use the @Observes annotation.
public class AccountObserver {
  void checkTran(@Observes Withdrawal w) {
    ...
  }
}

Example 10.18. Observe a qualified event

You can use qualifiers to observe only specific types of events. For more information about qualifiers, see Section 10.2.3.2, “About Qualifiers”.
public class AccountObserver {
  void checkTran(@Observes @Suspicious Withdrawal w) {
    ...
  }
}