SpringBoot系列教程web篇Listener四种注册姿势

java web三要素Filter, Servlet前面分别进行了介绍,接下来我们看一下Listener的相关知识点,本篇博文主要内容为SpringBoot环境下,如何自定义Listener并注册到spring容器

I. 环境配置

1. 项目搭建

首先我们需要搭建一个web工程,以方便后续的servelt注册的实例演示,可以通过spring boot官网创建工程,也可以建立一个maven工程,在pom.xml中如下配置

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/libs-snapshot-local</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/libs-milestone-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-releases</id>
        <name>Spring Releases</name>
        <url>https://repo.spring.io/libs-release-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

II. Listener注册

我们这里说到的Listener专指java web相关的监听器,与Spring本身的Listener并不一样。在java web中Listener的知识点为servlet规范的那一套,这里不详细展开。下面主要介绍在SpringBoot中使用Servlet Listener的四种方式

1. WebListener注解

@WebListener注解为Servlet3+提供的注解,可以标识一个类为Listener,使用姿势和前面的Listener、Filter并没有太大的区别

@WebListener
public class AnoContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("@WebListener context 初始化");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("@WebListener context 销毁");
    }
}

因为WebListener注解不是spring的规范,所以为了识别它,需要在启动类上添加注解@ServletComponentScan

@ServletComponentScan
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

2. 普通bean

第二种使用方式是将Listener当成一个普通的spring bean,spring boot会自动将其包装为ServletListenerRegistrationBean对象

@Component
public class BeanContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("bean context 初始化");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("bean context 销毁");
    }
}

3. ServletListenerRegistrationBean

通过java config来主动将一个普通的Listener对象,塞入ServletListenerRegistrationBean对象,创建为spring的bean对象

public class ConfigContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("config context 初始化");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("java context 销毁");
    }
}

上面只是一个普通的类定义,下面的bean创建才是关键点

@Bean
public ServletListenerRegistrationBean configContextListener() {
    ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean();
    bean.setListener(new ConfigContextListener());
    return bean;
}

4. ServletContextInitializer

这里主要是借助在ServletContext上下文创建的实际,主动的向其中添加Filter,Servlet, Listener,从而实现一种主动注册的效果

public class SelfContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContextInitializer context 初始化");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContextInitializer context 销毁");
    }
}

@Component
public class ExtendServletConfigInitializer implements ServletContextInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.addListener(SelfContextListener.class);
    }
}

注意ExtendServletConfigInitializer的主动注册时机,在启动时添加了这个Listenrer,所以它的优先级会是最高

5. 测试

上面介绍了四种注册方式,都可以生效,在我们的实际开发中,按需选择一种即可,不太建议多种方式混合使用;

项目启动和关闭之后,输出日志如下

II. 其他

web系列博文

项目源码

1. 一灰灰Blog

尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激

下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

原文地址:https://www.cnblogs.com/yihuihui/p/12034522.html

时间: 2024-07-30 01:24:23

SpringBoot系列教程web篇Listener四种注册姿势的相关文章

SpringBoot系列教程web篇之重定向

原文地址: SpringBoot系列教程web篇之重定向 前面介绍了spring web篇数据返回的几种常用姿势,当我们在相应一个http请求时,除了直接返回数据之外,还有另一种常见的case -> 重定向: 比如我们在逛淘宝,没有登录就点击购买时,会跳转到登录界面,这其实就是一个重定向.本文主要介绍对于后端而言,可以怎样支持302重定向 I. 环境搭建 首先得搭建一个web应用才有可能继续后续的测试,借助SpringBoot搭建一个web应用属于比较简单的活; 创建一个maven项目,pom文

SpringBoot系列教程web篇之404、500异常页面配置

接着前面几篇web处理请求的博文,本文将说明,当出现异常的场景下,如404请求url不存在,,403无权,500服务器异常时,我们可以如何处理 原文友链: SpringBoot系列教程web篇之404.500异常页面配置 I. 环境搭建 首先得搭建一个web应用才有可能继续后续的测试,借助SpringBoot搭建一个web应用属于比较简单的活; 创建一个maven项目,pom文件如下 <parent> <groupId>org.springframework.boot</gr

SpringBoot系列教程web篇之Beetl环境搭建

前面两篇分别介绍了目前流行的模板引擎Freemaker和Thymeleaf构建web应用的方式,接下来我们看一下号称性能最好的国产模板引擎Beetl,如何搭建web环境 本文主要来自官方文档,如有疑问,推荐查看: http://ibeetl.com/guide/#beetl I. 准备 1. 依赖 首先我们是需要一个springboot项目,基本的pom结构大都相似 <parent> <groupId>org.springframework.boot</groupId>

SpringBoot 系列教程之编程式事务使用姿势介绍篇

SpringBoot 系列教程之编程式事务使用姿势介绍篇 前面介绍的几篇事务的博文,主要是利用@Transactional注解的声明式使用姿势,其好处在于使用简单,侵入性低,可辨识性高(一看就知道使用了事务):然而缺点也比较明显,不够灵活,稍不注意,可能就因为姿势不对,导致事务不生效 本文将介绍另外一种事务的使用姿势,借助TransactionTemplate的编程式事务 I. 配置 本篇主要介绍的是jdbcTemplate+transactionTemplate来完成一个编程式事务的实例 de

SpringBoot 系列教程之事务不生效的几种 case

SpringBoot 系列教程之事务不生效的几种 case 前面几篇博文介绍了声明式事务@Transactional的使用姿势,只知道正确的使用姿势可能还不够,还得知道什么场景下不生效,避免采坑.本文将主要介绍让事务不生效的几种 case I. 配置 本文的 case,将使用声明式事务,首先我们创建一个 SpringBoot 项目,版本为2.2.1.RELEASE,使用 mysql 作为目标数据库,存储引擎选择Innodb,事务隔离级别为 RR 1. 项目配置 在项目pom.xml文件中,加上s

SpringBoot 系列教程之事务隔离级别知识点小结

SpringBoot 系列教程之事务隔离级别知识点小结 上一篇博文介绍了声明式事务@Transactional的简单使用姿势,最文章的最后给出了这个注解的多个属性,本文将着重放在事务隔离级别的知识点上,并通过实例演示不同的事务隔离级别下,脏读.不可重复读.幻读的具体场景 I. 基础知识 在进入正文之前,先介绍一下事务隔离级别的一些基础知识点,详细内容,推荐参考博文 mysql 之锁与事务 1. 基本概念 以下基本概念源于个人理解之后,通过简单的 case 进行描述,如有问题,欢迎拍砖 更新丢失

Provisioning Services 7.8 入门系列教程14篇全部完成了.....

经过近期一段时间的努力,Provisioning Services 7.8 入门系列教程14篇全部完成了-- Provisioning Services 7.8 入门系列教程之十四 UEFI支持和BOOTPTAB 编辑器 2016-05-14 Provisioning Services 7.8 入门系列教程之十三 使用 Boot Device Management(BDM)2016-05-13 Provisioning Services 7.8 入门系列教程之十二 实现高可用性 2016-05-

Struts2中访问web元素的四种方式

Struts2中访问web元素的四种方式如下: 通过ActionContext来访问Map类型的request.session.application对象. 通过实现RequestAware.SessionAware.ApplicationAware接口来访问Map类型的request.session.application对象(IoC方式). 通过ServletActionContext来访问Servlet API类型的HttpServletRequest. HttpSession. Serv

SpringBoot系列教程JPA之update使用姿势

原文: 190623-SpringBoot系列教程JPA之update使用姿势 上面两篇博文拉开了jpa使用姿势的面纱一角,接下来我们继续往下扯,数据插入db之后,并不是说就一层不变了,就好比我在银行开了户,当然是准备往里面存钱了,有存就有取(特别是当下银行利率这么低还不如买比特币屯着,截止19年6月22日,btc已经突破1.1w$,可惜没钱买??)这就是我们今天的主题,数据更新--update的使用姿势 通过本篇博文,您至少可以选到 save() 直接根据id来修改记录 利用jpl 实现查询修