Enterprise Java

Spring Boot ServletContextListener Registration

In Java web applications, the ServletContextListener plays an important role in monitoring the lifecycle of the ServletContext. It allows developers to perform custom logic during the startup and shutdown of the application context. In a Spring Boot application, we can register and use ServletContextListener seamlessly by leveraging Spring Boot’s configuration mechanisms. Let us delve into how to register servletcontextlistener in spring boot effectively for handling application lifecycle events.

1. Introduction to ServletContextListener in Spring

The ServletContextListener is part of the Java Servlet API. It listens to two lifecycle events:

  • contextInitialized() – Invoked when the web application is starting up. Ideal for resource initialization.
  • contextDestroyed() – Invoked when the web application is shutting down. Ideal for resource cleanup.

In a traditional servlet-based application, the listener is configured in the web.xml. However, in Spring Boot, since we do not use web.xml, we can register the listener using either:

  • Spring @Bean configuration
  • Spring Boot’s ServletListenerRegistrationBean
  • Or annotating the listener with @WebListener (when Servlet component scanning is enabled)

2. Code Example

2.1 Project Setup

We will use a simple Spring Boot project with the spring-boot-starter-web dependency specified in pom.xml.

  <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

2.2 Create a Custom ServletContextListener

The following code shows how to create a custom ServletContextListener in Spring Boot.

  package com.example.demo.listener;

  import jakarta.servlet.ServletContextEvent;
  import jakarta.servlet.ServletContextListener;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;

  public class AppServletContextListener implements ServletContextListener {

    private static final Logger logger = LoggerFactory.getLogger(AppServletContextListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        logger.info("ServletContext initialized. Application is starting up...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        logger.info("ServletContext destroyed. Application is shutting down...");
    }
  }

In the listener class, we create a listener class AppServletContextListener that implements ServletContextListener. Inside the contextInitialized() method, we log a message when the application context starts, and in the contextDestroyed() method, we log a message when the context shuts down. This allows us to track the application lifecycle events and perform custom initialization or cleanup tasks as needed.

2.3 Register Listener in Spring Boot

The following code demonstrates how to register the custom ServletContextListener in a Spring Boot application using ServletListenerRegistrationBean.

  package com.example.demo.config;

  import com.example.demo.listener.AppServletContextListener;
  import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
  import org.springframework.context.annotation.Bean;
  import org.springframework.context.annotation.Configuration;

  @Configuration
  public class ListenerConfig {

    @Bean
    public ServletListenerRegistrationBean<AppServletContextListener> servletListener() {
        ServletListenerRegistrationBean<AppServletContextListener> listenerRegBean =
                new ServletListenerRegistrationBean<>(new AppServletContextListener());
        return listenerRegBean;
    }
  }

Here, we create a configuration class ListenerConfig annotated with @Configuration. Inside it, a Spring bean of type ServletListenerRegistrationBean is defined, which takes our custom AppServletContextListener as an argument. This bean tells Spring Boot to register the listener with the embedded servlet container, enabling it to receive context lifecycle events during application startup and shutdown.

2.4 Main Application Class

The following code defines the main entry point of the Spring Boot application.

  package com.example.demo;

  import org.springframework.boot.SpringApplication;
  import org.springframework.boot.autoconfigure.SpringBootApplication;

  @SpringBootApplication
  public class ServletListenerDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServletListenerDemoApplication.class, args);
    }
  }

In this code, the ServletListenerDemoApplication class is annotated with @SpringBootApplication, which enables auto-configuration, component scanning, and configuration properties in Spring Boot. The main() method invokes SpringApplication.run(), which starts the embedded servlet container (Tomcat by default) and initializes the Spring application context.

2.5 Sample REST Controller

The following code shows a simple REST controller that exposes a test endpoint.

  package com.example.demo.controller;

  import org.springframework.web.bind.annotation.GetMapping;
  import org.springframework.web.bind.annotation.RestController;

  @RestController
  public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot with ServletContextListener!";
    }
  }

Here, we define a REST controller HelloController annotated with @RestController. It exposes a single GET endpoint /hello using the @GetMapping annotation. When this endpoint is accessed, it returns a plain text message “Hello, Spring Boot with ServletContextListener!”, which helps us verify that the application and the registered listener are working correctly.

2.6 Expected Output

When the application starts, you will see the following logs in the console:

  INFO  --- ServletContext initialized. Application is starting up...

When you stop the application, you will see:

  INFO  --- ServletContext destroyed. Application is shutting down...

And when you access http://localhost:8080/hello in your browser or using curl:

  Hello, Spring Boot with ServletContextListener!

3. Conclusion

The ServletContextListener in Spring Boot provides a clean way to hook into the application’s startup and shutdown lifecycle. By registering a custom listener, you can initialize resources at startup and release them during shutdown. In Spring Boot, you can easily register a listener via ServletListenerRegistrationBean or @WebListener, making the integration seamless. This approach is particularly useful for scenarios such as setting up caches, scheduling jobs, or cleaning up resources when the application terminates.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button