6.27 Server Events

The HTTP server will emit a number of Bean Events, defined in the io.micronaut.runtime.server.event package, that you can write listeners for. The following table summarizes those events:

Table 1. Server Events
EventDescription

ServerStartupEvent

Emitted when the server completes startup

ServerShutdownEvent

Emitted when the server shuts down

ServiceReadyEvent

Emitted after all ServerStartupEvent listeners have been executed and exposes the EmbeddedServerInstance

ServiceStoppedEvent

Emitted after all ServerShutdownEvent listeners have been executed and exposes the EmbeddedServerInstance

If you do significant work within a listener for a ServerStartupEvent this will slow down you startup time.

The following example defines a ApplicationEventListener that listens for ServerStartupEvent:

Listening for Server Startup Events

  1. import io.micronaut.context.event.ApplicationEventListener;
  2. ...
  3. @Singleton
  4. public class StartupListener implements ApplicationEventListener<ServerStartupEvent> {
  5. @Override
  6. public void onApplicationEvent(ServerStartupEvent event) {
  7. // logic here
  8. ...
  9. }
  10. }

Alternatively, you can also use the @EventListener annotation on a method of any existing bean that accepts ServerStartupEvent:

Using @EventListener with ServerStartupEvent

  1. import io.micronaut.runtime.server.event.*;
  2. import io.micronaut.runtime.event.annotation.*;
  3. ...
  4. @Singleton
  5. public class MyBean {
  6. @EventListener
  7. public void onStartup(ServerStartupEvent event) {
  8. // logic here
  9. ...
  10. }
  11. }