`

详解Spring中的ApplicationListener和ContextRefreshedEvent

 
阅读更多

 

转自:https://www.xttblog.com/?p=2053

 

事件机制作为一种编程机制,在许多语言中都提供了支持。JAVA语言也不例外,java中的事件机制的参与者有3种角色:

  1. event object
  2. event source
  3. event listener

这三个角色的含义字面上很好解,它们就定义了事件机制的一个基本模型。作为一种常用的编程设计机制,许多开源框架的设计中都使用了事件机制。SpringFramework也不例外。

在IOC的容器的启动过程,当所有的bean都已经处理完成之后,spring ioc容器会有一个发布事件的动作。从 AbstractApplicationContext 的源码中就可以看出:

1
2
3
4
5
6
7
8
9
10
11
protected void finishRefresh() {
    // Initialize lifecycle processor for this context.
    initLifecycleProcessor();
    // Propagate refresh to lifecycle processor first.
    getLifecycleProcessor().onRefresh();
    // Publish the final event.
    publishEvent(new ContextRefreshedEvent(this));
    // 业余草:www.xttblog.com
    // Participate in LiveBeansView MBean, if active.
    LiveBeansView.registerApplicationContext(this);
}

这样,当ioc容器加载处理完相应的bean之后,也给我们提供了一个机会(先有InitializingBean,后有ApplicationListener<ContextRefreshedEvent>),可以去做一些自己想做的事。其实这也就是spring ioc容器给提供的一个扩展的地方。我们可以这样使用这个扩展机制。

1
2
org.springframework.context.ApplicationEvent
org.springframework.context.ApplicationListener

一个最简单的方式就是,让我们的bean实现ApplicationListener接口,这样当发布事件时,spring的ioc容器就会以容器的实例对象作为事件源类,并从中找到事件的监听者,此时ApplicationListener接口实例中的onApplicationEvent(E event)方法就会被调用,我们的逻辑代码就会写在此处。这样我们的目的就达到了。但这也带来一个思考,有人可能会想,这样的代码我们也可以通过实现spring的InitializingBean接口来实现啊,也会被spring容器去自动调用,但是大家应该想到,如果我们现在想做的事,是必须要等到所有的bean都被处理完成之后再进行,此时InitializingBean接口的实现就不合适了,所以需要深刻理解事件机制的应用场合。

曾经有一位同事利用 ApplicationListener,重复加载了好几次 xml 配置文件。所以基础知识一定要掌握。

下面是一个完整的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {
    private static Logger _log = LoggerFactory.getLogger(ApplicationContextListener.class);
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // root application context
        if(null == contextRefreshedEvent.getApplicationContext().getParent()) {
            _log.debug(">>>>> spring初始化完毕 <<<<<");
            // spring初始化完毕后,通过反射调用所有使用BaseService注解的initMapper方法
            Map<String, Object> baseServices =
            contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(BaseService.class);
            for(Object service : baseServices.values()) {
                _log.debug(">>>>> {}.initMapper()", service.getClass().getName());
                try {
                    Method initMapper = service.getClass().getMethod("initMapper");
                    initMapper.invoke(service);
                catch (Exception e) {
                    _log.error("初始化BaseService的initMapper方法异常", e);
                    e.printStackTrace();
                }
            }
            // 系统入口初始化,业余草:www.xttblog.com
            Map<String, BaseInterface> baseInterfaceBeans =
            contextRefreshedEvent.getApplicationContext().getBeansOfType(BaseInterface.class);
            for(Object service : baseInterfaceBeans.values()) {
                _log.debug(">>>>> {}.init()", service.getClass().getName());
                try {
                    Method init = service.getClass().getMethod("init");
                    init.invoke(service);
                catch (Exception e) {
                    _log.error("初始化BaseInterface的init方法异常", e);
                    e.printStackTrace();
                }
            }
        }
    }
}

以上就是ApplicationListener和ContextRefreshedEvent的相关用法。

分享到:
评论

相关推荐

    Spring ApplicationListener的使用详解

    Spring ApplicationListener的使用详解 Spring ApplicationListener是Spring事件机制的一部分,通常与ApplicationEvent抽象类结合完成ApplicationContext的事件通知机制。下面我们将详细介绍Spring Application...

    Spring ApplicationListener监听器用法详解

    本文主要介绍了Spring框架中的ApplicationListener监听器的用法详解,通过示例代码对 listeners 的实现和使用进行了详细的讲解,对大家的学习或者工作具有一定的参考学习价值。 一、什么是ApplicationListener? ...

    详解spring boot容器加载完后执行特定操作

    在上面的示例代码中,我们创建了一个实现 ApplicationListener 接口的类 ApplicationStartup,该类用于监听 ContextRefreshedEvent 事件。在事件处理方法 onApplicationEvent 中,我们获取了 DAO 层和配置文件中的...

    详解Spring事件驱动模型

    在Spring中,事件对象通常是`ApplicationEvent`的子类,发布事件的方法是`ApplicationContext`提供的`publishEvent`。当事件被发布时,所有已注册的`ApplicationListener`都会收到通知,执行相应的事件处理逻辑。 ...

    SpringMVC事件监听ApplicationListener实例解析

    其中,ApplicationListener就是SpringMVC框架中的一种事件监听器,允许开发者监听框架中的各种事件。 要使用ApplicationListener,需要实现ApplicationListener接口,其中T是监听的事件类型。例如,想要监听...

    基于Spring的listener和Task

    在Spring框架中,Listener和Task是两种非常关键的组件,它们在后端开发中起着至关重要的作用。本文将深入探讨这两个概念以及如何在实际应用中利用它们。 首先,我们来了解一下Spring的Listener。在Java Web开发中,...

    spring运行过程中动态注册bean

    在实际开发中,我们往往需要在应用启动后动态注册Bean,这时候可以利用`BeanFactoryAware`接口和`ApplicationListener`接口。`BeanFactoryAware`接口使得Bean可以被注入`BeanFactory`,而`ApplicationListener`接口...

    详解Spring中bean的scope以后使用

    本文将详细介绍Spring中不同作用域的Bean,包括它们的特点、应用场景以及配置方法。 #### 二、作用域概述 Spring框架提供了多种作用域来适应不同的应用场景。这些作用域包括: 1. **Singleton** 2. **Prototype**...

    TODO Spring注解驱动开发第38讲——你知道ApplicationListener的用法吗?

    TODO Spring注解驱动开发第38讲——你知道ApplicationListener的用法吗?

    TODO Spring注解驱动开发第39讲——你不知道的ApplicationListener的原理

    TODO Spring注解驱动开发第39讲——你不知道的ApplicationListener的原理

    详解Spring中bean的作用域

    Spring中bean的作用域详解 Spring 中 bean 的作用域是指 Spring IoC 容器中 bean 的生命周期和实例化方式。bean 的作用域决定了 bean 的实例化和生命周期的管理方式。在 Spring 中,bean 的作用域可以分为五种:...

    让spring解决控制springboot中bean的加载顺序的问题.docx

    虽然@Order不能直接控制所有Bean的加载顺序,但它在AOP切面、ApplicationListener和CommandLineRunner的排序中非常有用。例如,如果你有两个监听器类需要按照特定顺序执行,可以这样设置: ```java @Component @...

    spring源码中英文注释

    `ApplicationEvent`和`ApplicationListener`接口是实现事件驱动的关键。 9. **国际化与本地化**:Spring提供了`MessageSource`接口来支持多语言环境。源码中会涉及资源文件的加载和消息的查找。 10. **SpEL...

    Spring事件Application Event原理详解

    Spring 事件 Application Event 原理详解 Spring 事件 Application Event 是 Spring 框架中的一种消息通信机制,用于实现 Bean 之间的消息传递。该机制基于观察者模式,允许一个 Bean 处理完一个任务之后,通知...

    Spring启动后获取所有拥有特定注解的Bean实例代码

    Spring启动后获取所有拥有特定注解的Bean实例代码可以通过实现ApplicationListener&lt;ContextRefreshedEvent&gt;接口来实现,这种方式可以实现系统参数的初始化,获取系统中所有接口服务清单等一系列需要在Spring启动后...

    spring配置activemq详解

    在"spring配置activemq详解"这个主题中,我们将探讨如何在Spring项目中配置和使用ActiveMQ。以下是对这个主题的详细说明: 1. **配置ActiveMQ**: - 首先,我们需要在项目中引入ActiveMQ的相关依赖,这通常通过在`...

    Spring Boot的listener(监听器)简单使用实例详解

    在Spring Boot中,listener(监听器)是一种非常重要的组件,它可以帮助我们在应用程序启动和停止时执行一些特定的任务。今天,我们将详细介绍Spring Boot的listener(监听器)简单使用实例详解。 一、listener...

    详解SpringBoot程序启动时执行初始化代码

    SpringBoot程序启动时...我们可以使用ApplicationListener接口、CommandLineRunner接口和EnvironmentAware接口来实现初始化代码,并在SpringBootApplication中注册我们刚创建的类,以便在程序启动时执行初始化代码。

    Spring+mvc+mybatis Mapper xml自动加载

    public class MybatisConfigChangeListener implements ApplicationListener&lt;ContextRefreshedEvent&gt; { @Override public void onApplicationEvent(ContextRefreshedEvent event) { // 检查并重新加载XML文件 } ...

Global site tag (gtag.js) - Google Analytics