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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
解决SpringMVC Controller 接收页面传递的中文参数出现乱码的问题
下面小编就为大家分享一篇解决SpringMVC Controller 接收页面传递的中文参数出现乱码的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-03-03
SpringBoot+EasyPOI轻松实现Excel和Word导出PDF
在企业级开发中,将 Excel 和 Word 文档导出为 PDF 是常见需求,本文将结合 EasyPOI和 Aspose 系列工具实现 Excel 和 Word 到 PDF 的转换,需要的可以了解下2025-07-07
java 定时器线程池(ScheduledThreadPoolExecutor)的实现
这篇文章主要介绍了java 定时器线程池(ScheduledThreadPoolExecutor),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-06-06


最新评论