Springboot使用@WebListener 作为web监听器的过程解析
一、使用@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);
}
}到此这篇关于Springboot使用@WebListener 作为web监听器的文章就介绍到这了,更多相关Springboot 使用@WebListener内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot2零基础到精通之JUnit 5与指标监控
SpringBoot是一种整合Spring技术栈的方式(或者说是框架),同时也是简化Spring的一种快速开发的脚手架,本篇让我们一起学习JUnit 5与指标监控2022-03-03
简述springboot及springboot cloud环境搭建
这篇文章主要介绍了简述springboot及springboot cloud环境搭建的方法,包括spring boot 基础应用环境搭建,需要的朋友可以参考下2017-07-07
利用Mybatis向PostgreSQL中插入并查询JSON字段
这篇文章主要介绍了利用Mybatis向PostgreSQL中插入并查询JSON字段,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下2022-07-07


最新评论