onApplicationEvent method

  1. @override
void onApplicationEvent(
  1. ApplicationContextEvent event
)
override

Handle an application event of type E.

This method will be called by the event publisher when an event of type E (or subtype) is dispatched. The method should process the event and return promptly to avoid blocking event dispatch to other listeners.

Parameters:

  • event: The application event that occurred. This will always be an instance of type E or one of its subtypes.

Implementation Notes:

  • Keep event handling logic minimal and efficient
  • Consider offloading long-running operations to separate executors
  • Handle exceptions appropriately within the method
  • Avoid modifying the event object unless documented as safe

Example:

@override
void onApplicationEvent(UserRegisteredEvent event) {
  final user = event.user;
  logger.info('User registered: ${user.username}');
  
  // Send welcome email
  emailService.sendWelcomeEmail(user.email);
}

Error Handling:

If an exception is thrown during event processing:

  • The exception is caught and logged by the event publisher
  • Other listeners will still receive the event
  • The publishing code is not affected by the exception

See also:

Implementation

@override
void onApplicationEvent(ApplicationContextEvent event) {
  if (event is ContextRefreshedEvent) {
    startKeepAliveThread();
  } else if (event is ContextClosedEvent) {
    stopKeepAliveThread();
  }
}