Helidon: Startup and Shutdown hook

0
51

When you build a real-time microservice application, you may need a listener for startup and shutdown events. This might be very simple and straight forward when we implement our application using Servlet APIs. We can simply provide an implementation of ServletContextListener and listen to a specific lifecycle event of our choice. Now the question is how this can be achieved using the Helidon framework? The answer is also very simple but we may need to take a different approach using the CDI lifecycle.

How?

@ApplicationScoped
public class DailyApiBootListener {
    public void init(@Observes @Initialized(ApplicationScoped.class)
                             final Object init) {
        System.out.println("Init part is called");
        System.out.println(init.getClass().getName());
    }

    public void beforeDestroy(@Observes @BeforeDestroyed(ApplicationScoped.class)
                                Object init) {
        System.out.println("Before Destroy is called");
    }

    public void destroy(@Observes @Destroyed(ApplicationScoped.class)
                                Object init) {
        System.out.println("Destroy is called");
    }
}

Inside the methods, we can write the necessary code and achieve whatever is needed in our business use-cases.

ApplicationScoped is also an annotation provided by CDI specification. All the CDI beans will be scanned automatically during the start of the server. So that we can easily attach our listeners during the lifecycle of the CDI beans.

I hope this would solve your use-cases. Please share this article if this is useful to you.

{ Happy coding }