一、定义ServletContextListener:

package com.example.config;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyServletContextListener implements ServletContextListener {

@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("init......");
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("destroyed......");
}
}

2.配置ServletListenerRegistrationBean

package com.example.config;

import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServletListenerRegistrationConfig {

@Bean
public ServletListenerRegistrationBean<MyServletContextListener> initServletListenerRegistrationBean() {
ServletListenerRegistrationBean<MyServletContextListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>();
servletListenerRegistrationBean.setListener(new MyServletContextListener());

return servletListenerRegistrationBean;
}


}

3.启动应用,可以看到输出:

SpringBoot 官方文档示例:(60)使用ServletListenerRegistrationBean注册ServletContextListener_spring boot