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:
Event | Description |
---|---|
Emitted when the server completes startup | |
Emitted when the server shuts down | |
Emitted after all ServerStartupEvent listeners have been invoked and exposes the EmbeddedServerInstance | |
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
import io.micronaut.context.event.ApplicationEventListener;
...
@Singleton
public class StartupListener implements ApplicationEventListener<ServerStartupEvent> {
@Override
public void onApplicationEvent(ServerStartupEvent event) {
// logic here
...
}
}
Alternatively, you can also use the @EventListener annotation on a method of any bean that accepts ServerStartupEvent
:
Using @EventListener
with ServerStartupEvent
import io.micronaut.runtime.event.annotation.EventListener;
import io.micronaut.runtime.server.event.ServerStartupEvent;
import javax.inject.Singleton;
...
@Singleton
public class MyBean {
@EventListener
public void onStartup(ServerStartupEvent event) {
// logic here
...
}
}