一、使用@WebListener 作为web监听器
1、使用监听器必须在启动类上添加扫描
- @ServletComponentScan
@ServletComponentScan
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
二、Listener的四种注册方式
1、@WebListener 注解方式
示例1:Session监听器
- @WebListener 本质上是事件监听
- HttpSessionListener和HttpSessionAttributeListener都是实现了EventListener接口
@WebListener
public class SessionListener implements HttpSessionAttributeListener, HttpSessionListener {
// ... ... 省略实现方法
}
示例2:属性监听器
@WebListener
public class ContextListener implements ServletContextAttributeListener,ServletContextListener {
// ... ... 省略实现方法
}
2、普通Bean方式
1、创建监听器类
将 Listener 当成一个普通的 spring bean,spring boot 会自动将其包装为ServletListenerRegistrationBean
对象
- ServletContextListener 需要实现该接口
- contextInitialized 容器初始化接口
- contextDestroyed 容器销毁方法
@Component
public class BeanContextListener implements ServletContextListener {
// ... ... 省略实现方法
}
3、Bean手动注册方式
1、创建一个配置监听类
- ServletContextListener 主动注入
public class ConfigContextListener implements ServletContextListener {
// ... .... 省略实现方法
}
2、通过配置监听类将自定义监听类注册
@Bean
public ServletListenerRegistrationBean configContextListener() {
ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean();
bean.setListener(new ConfigContextListener());
return bean;
}
4、上下文初始化方式
在初始化类中注入监听器
1、创建监听器
public class SelfContextListener implements ServletContextListener {
// ... ... 省略实现方法
}
2、 使用上下文添加监听器
@Component
public class ExtendServletConfigInitializer implements ServletContextInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addListener(SelfContextListener.class);
}
}