Skip to content

Commit 3fa0375

Browse files
[BAEL-9350] Register ServletContextListener in Spring Boot
- implement two different ways of registering a custom ServletContextListener
1 parent 0e6edf1 commit 3fa0375

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.servletcontextlistener;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
import jakarta.servlet.ServletContextEvent;
7+
import jakarta.servlet.ServletContextListener;
8+
9+
// Annotate with @WebListener if using @ServletComponentScan in ServletContextListenerApplication
10+
public class CustomLifecycleLoggingListener implements ServletContextListener {
11+
12+
private final Logger log = LoggerFactory.getLogger(CustomLifecycleLoggingListener.class);
13+
14+
@Override
15+
public void contextInitialized(ServletContextEvent sce) {
16+
log.info("Application started");
17+
}
18+
19+
@Override
20+
public void contextDestroyed(ServletContextEvent sce) {
21+
log.info(" Application stopped");
22+
}
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.servletcontextlistener;
2+
3+
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
4+
import org.springframework.context.annotation.Bean;
5+
import org.springframework.context.annotation.Configuration;
6+
7+
@Configuration
8+
public class CustomListenerConfiguration {
9+
10+
@Bean
11+
public ServletListenerRegistrationBean<CustomLifecycleLoggingListener> lifecycleListener() {
12+
return new ServletListenerRegistrationBean<>(new CustomLifecycleLoggingListener());
13+
}
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.servletcontextlistener;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
// @ServletComponentScan enables scanning for servlet components such as @WebListener, @WebFilter, and @WebServlet.
8+
public class ServletContextListenerApplication {
9+
10+
public static void main(String[] args) {
11+
SpringApplication.run(ServletContextListenerApplication.class, args);
12+
}
13+
}

0 commit comments

Comments
 (0)