Spring Boot (Web 篇):整合监听器Listener

版权声明:本博客所有内容采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可 https://blog.csdn.net/Soinice/article/details/82869919

说在前面

Listener简介:https://blog.csdn.net/Soinice/article/details/82787964

上一篇文章已经对定义Filter 的方法进行了说明,监听器(Listener)的注册方法和Filter一样,不清楚的可以查看下上一篇文章:https://blog.csdn.net/Soinice/article/details/82801002

在spring boot中添加自己的Listener有两种方法,代码注册Listener和注解自动注册(Servlet和Filter也是如此)。

 一、代码注册通过ServletListenerRegistrationBean 获得控制。  也可以通过实现 ServletContextInitializer 接口直接注册。

 二、在 SpringBootApplication 上使用@ServletComponentScan注解后,Listener可以直接通过 @WebListener注解自动注册,无需其他代码。

在pom.xml加入相关依赖

当然,通过idea 创建默认spring boot web 项目,会默认含有这个属性

1)通过ServletListenerRegistrationBean进行代码注册

编写监听器 Listener

注册监听器 Listener

将 Listener 注册成 Bean。在上文创建的 WebMvcConfig类中添加如下代码:

页面访问(项目启动)

2)通过注解@ServletComponentScan进行代码注册

编写监听器 Listener

在Listener 类添加注解@WebListener:

注册监听器 Listener

将 Servelt 进行组件扫描。在应用启动SpringBootDemoApplication类中添加注解@ServletComponentScan:

页面访问(项目启动)

总结

Servlet的监听器Listener,它是实现了javax.servlet.ServletContextListener 接口的服务器端程序,它也是随web应用的启动而启动,只初始化一次,随web应用的停止而销毁。

主要作用是:做一些初始化的内容添加工作、设置一些基本的内容、比如一些参数或者是一些固定的对象等等。

源码下载

[相关示例完整代码]请获取 相关分支哦:feature-20180910-web

猜你喜欢

转载自blog.csdn.net/Soinice/article/details/82869919
今日推荐