Spring中ApplicationListener的使用解析

 更新时间:2023年12月25日 10:59:57   作者:云川之下  
这篇文章主要介绍了Spring中ApplicationListener的使用解析,ApplicationContext事件机制是观察者设计模式的实现,通过ApplicationEvent类和ApplicationListener接口,需要的朋友可以参考下

背景

ApplicationContext事件机制是观察者设计模式的实现,通过ApplicationEvent类和ApplicationListener接口,可以实现ApplicationContext事件处理;

如果容器中存在ApplicationListener的Bean,当ApplicationContext调用publishEvent方法时,对应的Bean会被触发。

spring内置事件

  • ContextRefreshedEvent ApplicationContext 被初始化或刷新时,该事件被触发。这也可以在 ConfigurableApplicationContext接口中使用 refresh() 方法来发生。此处的初始化是指:所有的Bean被成功装载,后处理Bean被检测并激活,所有Singleton Bean 被预实例化,ApplicationContext容器已就绪可用
  • ContextStartedEvent 当使用 ConfigurableApplicationContext (ApplicationContext子接口)接口中的 start() 方法启动 ApplicationContext 时,该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序。
  • ContextStoppedEvent 当使用 ConfigurableApplicationContext 接口中的 stop() 停止 ApplicationContext 时,发布这个事件。你可以在接受到这个事件后做必要的清理的工作。
  • ContextClosedEvent 当使用 ConfigurableApplicationContext 接口中的 close() 方法关闭 ApplicationContext 时,该事件被发布。一个已关闭的上下文到达生命周期末端;它不能被刷新或重启。
  • RequestHandledEvent 这是一个 web-specific 事件,告诉所有 bean HTTP 请求已经被服务。只能应用于使用DispatcherServlet的Web应用。在使用Spring作为前端的MVC控制器时,当Spring处理用户请求结束后,系统会自动触发该事件。

同样事件可以自定义、监听也可以自定义,完全根据自己的业务逻辑来处理。

ApplicationListener源码

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
    /**
     * Handle an application event.
     * @param event the event to respond to
     */
    void onApplicationEvent(E event);
}

ContextRefreshedEvent事件的监听

以Spring的内置事件ContextRefreshedEvent为例,当ApplicationContext被初始化或刷新时,会触发ContextRefreshedEvent事件,下面我们就实现一个ApplicationListener来监听此事件的发生。

@Component
public class MyListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("容器中初始化Bean数量:" + event.getApplicationContext().getBeanDefinitionCount());
    }
}

启动服务,可以看到

在这里插入图片描述

至此,便完成了一个事件及监听类的实现和实例化。

自定义事件及监听,以发送邮件为例

自定义邮件通知事件类:EmailEvent

package com.lw.coodytest.event;
import org.springframework.context.ApplicationEvent;
/**
 * @Classname EmailEvent
 * @Description 邮件通知事件
 * @Author lw
 * @Date 2019-12-20 11:05
 */
public class EmailEvent extends ApplicationEvent {
    private String email;
    private String content;
    public EmailEvent(Object source){
        super(source);
    }
    public EmailEvent(Object source, String email, String content){
        super(source);
        this.email = email;
        this.content = content;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

自定义邮件通知监听类:EmailListener:

package com.lw.coodytest.event;
import org.springframework.context.ApplicationEvent;
/**
 * @Classname EmailEvent
 * @Description 邮件通知事件
 * @Author lw
 * @Date 2019-12-20 11:05
 */
public class EmailEvent extends ApplicationEvent {
    private String email;
    private String content;
    public EmailEvent(Object source){
        super(source);
    }
    public EmailEvent(Object source, String email, String content){
        super(source);
        this.email = email;
        this.content = content;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

注意:onApplicationEvent方法的入参,必须是自定义的那个类型

单元测试类:

package com.lw.coodytest.junit;
import com.lw.coodytest.event.EmailEvent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;
/**
 * @Classname ListenerTest
 * @Description 监听测试类
 * @Author lw
 * @Date 2019-12-20 11:12
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ListenerTest {
    @Autowired
    private WebApplicationContext webapplicationcontext;
    @Test
    public void testListener(){
        EmailEvent emailEvent = new EmailEvent("object", "172572575@qq.com", "###listener");
        webapplicationcontext.publishEvent(emailEvent);
    }
}

监听器通过@Component注解进行实例化,并在onApplicationEvent中打印相关信息: 执行测试类,可以看到

在这里插入图片描述

至此,便完成了一个自定义事件及监听类的实现和实例化。

特别注意:不管是内置监听还是外部自定义监听一定要把实现ApplicationListener的类定义成一个bean才行,可以通过注解@Component或者在bean.xml中定义来实现。

也就是说通过注册为bean,才能实现事件的绑定。

到此这篇关于Spring中ApplicationListener的使用解析的文章就介绍到这了,更多相关ApplicationListener的使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Spring Security密码编辑器示例详解

    Spring Security密码编辑器示例详解

    本文介绍了Spring Security的密码编码机制及其在Maven项目管理中的配置方式,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2025-10-10
  • 使用SpringBoot编写一个优雅的单元测试

    使用SpringBoot编写一个优雅的单元测试

    这篇文章主要为大家详细介绍了如何使用SpringBoot编写一个优雅的单元测试,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起了解一下
    2023-07-07
  • Spring5中SpringWebContext方法过时的解决方案

    Spring5中SpringWebContext方法过时的解决方案

    这篇文章主要介绍了Spring5中SpringWebContext方法过时的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • 关于SpringBoot静态资源路径管理问题

    关于SpringBoot静态资源路径管理问题

    这篇文章主要介绍了SpringBoot静态资源路径管理,主要包括默认静态资源路径,增加静态资源路径前缀的相关操作,本文给大家介绍的非常详细,需要的朋友可以参考下
    2022-05-05
  • SpringBoot中使用com.alibaba.druid.filter.config.ConfigTools对数据库密码加密的方法

    SpringBoot中使用com.alibaba.druid.filter.config.ConfigTools对数据库

    这篇文章主要介绍了SpringBoot中使用com.alibaba.druid.filter.config.ConfigTools对数据库密码加密的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • SpringBoot集成POI导出Execl表格之统一工具类

    SpringBoot集成POI导出Execl表格之统一工具类

    这篇文章主要为大家详细介绍了SpringBoot集成POI导出Execl表格之统一工具类,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-09-09
  • 编写Spring MVC控制器的14个技巧(小结)

    编写Spring MVC控制器的14个技巧(小结)

    这篇文章主要介绍了编写Spring MVC控制器的14个技巧,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • SpringBoot因为jackson版本问题启动失败的解决

    SpringBoot因为jackson版本问题启动失败的解决

    SpringBoot启动失败解决Jackson版本冲突,通过调整pom.xml中的Jackson依赖版本,确保与SpringBoot兼容,避免启动时的嵌入容器初始化异常
    2026-05-05
  • Java中实现对中文字符的精确判断的方法

    Java中实现对中文字符的精确判断的方法

    在开发涉及多语言处理的应用时,经常需要对输入的文本进行语言或字符类型的判断,特别是在中文环境下,准确地识别中文字符对于文本处理、数据验证等操作至关重要,本文将介绍如何在Java中实现对中文字符的精确判断,需要的朋友可以参考下
    2025-12-12
  • java中redis增删查以及清理缓存的案例

    java中redis增删查以及清理缓存的案例

    这篇文章主要介绍了java中redis增删查以及清理缓存的案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02

最新评论