SpringBoot 官方文档示例:(60)使用ServletListenerRegistrationBean注册ServletContextListener
原创
©著作权归作者所有:来自51CTO博客作者wx62e0d796b5814的原创作品,请联系作者获取转载授权,否则将追究法律责任
一、定义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.启动应用,可以看到输出: