I am developing a Microservice application with Helidon MP. So far my experience is awesome. But I end up looking for a startup / shutdown hook with Helidon MP. I tried to find through search and Helidon Javadoc. But I am not able to find anything useful.
Do we have such functionality available with Helidon MP / Microprofile?
If you're using Helidon MP, then you're using CDI 2.0 under the covers. So this question reduces to: "Is there a way to be notified when a CDI container comes up and when it goes down?"
If you have a CDI bean (usually something annotated with @ApplicationScoped
or @Dependent
or @RequestScoped
), then you can add an observer method to it that is notified when the context denoted by a particular scope annotation (such as ApplicationScoped
) is initialized or destroyed. The initialization of the application scope is pretty much what you want, since it's roughly equivalent to "when the application starts", so here's how you would do that in any CDI application (Helidon MP included):
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Initialized;
import javax.enterprise.event.Observes;
private final void onStartup(@Observes @Initialized(ApplicationScoped.class) final Object event) {
// Do what you want; the CDI container has come up and everything
// is open for business
}
If you want to know right before everything goes down, you would do this:
private final void rightBeforeShutdown(@Observes @BeforeDestroyed(ApplicationScoped.class) final Object event) {
// Do what you want; the CDI container is just about to go down
}
Please note that as documented in the specification observer methods may be named anything you like, must have one parameter annotated with @Observes
, usually return void
and may be of any protection level.