Helidon: Startup and Shutdown hook

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 }

API Evangelist | Chief Hustler @workrituals.com | Habit Coach | Madras Java User Group Leader
81FollowersFollow
0SubscribersSubscribe

Latest articles

Jakarta Tech Talk: Build Microservice using Microprofile + Helidon

Recently I gave a presentation on Jakarta Tech Talk series on 'Building a Microservice using Microprofile + Helidon. Enjoy watching the presentation...

Serverless REST APIs made simple with Cloud functions

Introduction Serverless is one of the top keyword in the integration space right now. Everyone is talking about the...

How to get started with Google cloud functions?

The 'Cloud Functions' is a Google technology bundled as part of the Firebase platform. It is a serverless backend to support our...

Why Firebase is a great technology for ‘Indie Makers’...

Firebase is a technology developed by Google. In this article, I am going to explore why Firebase is a great technology for...

Helidon: 2x productivity with Microprofile REST Client

We have already many articles before on how to write Microservice using the Helidon framework. We are going to further enhance our...

Similar articles