6.28 Server Events

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

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 invoked and exposes the EmbeddedServerInstance

ServiceStoppedEvent

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

Doing significant work within a listener for a ServerStartupEvent will increase 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 bean that accepts ServerStartupEvent:

Using @EventListener with ServerStartupEvent

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