首页 > 代码库 > SpringBoot 之事件发布系统

SpringBoot 之事件发布系统

springboot应用,启动spring容器大致有如下几个过程:

  • 容器开始启动
  • 初始化环境变量
  • 初始化上下文
  • 加载上下文
  • 完成

对应的Spring应用的启动器的监听器可以监听以上的过程,接口如下:

技术分享
 1 public interface SpringApplicationRunListener { 2  3     /** 4      * Called immediately when the run method has first started. Can be used for very 5      * early initialization. 6      */ 7     void started(); 8  9     /**10      * Called once the environment has been prepared, but before the11      * {@link ApplicationContext} has been created.12      * @param environment the environment13      */14     void environmentPrepared(ConfigurableEnvironment environment);15 16     /**17      * Called once the {@link ApplicationContext} has been created and prepared, but18      * before sources have been loaded.19      * @param context the application context20      */21     void contextPrepared(ConfigurableApplicationContext context);22 23     /**24      * Called once the application context has been loaded but before it has been25      * refreshed.26      * @param context the application context27      */28     void contextLoaded(ConfigurableApplicationContext context);29 30     /**31      * Called immediately before the run method finishes.32      * @param context the application context or null if a failure occurred before the33      * context was created34      * @param exception any run exception or null if run completed successfully.35      */36     void finished(ConfigurableApplicationContext context, Throwable exception);37 38 }
监听器

对应几个关键事件

技术分享

监听器接口中的每个方法代表容器启动过程一个阶段,每一个阶段可以自定义执行一系列任务。可以将SpringApplicationRunListener理解成一个命令模式(传入一个对象,至于当前这个时间点,如何调用,不关心)。SpringApplicationRunListener有一个特殊的实现EventPublishingRunListener,他的主要功能就是,在特定时间点出发特殊事件。

@Override    public void started() {        this.initialMulticaster.multicastEvent(new ApplicationStartedEvent(                this.application, this.args));    }    @Override    public void environmentPrepared(ConfigurableEnvironment environment) {        this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(                this.application, this.args, environment));    }

SpringApplicationRunListeners是对多个SpringApplicationRunListener做了一次代理,聚合多个SpringApplicationRunListener,在任一个过程完成,会依次调用对应方法。

    private final List<SpringApplicationRunListener> listeners;    SpringApplicationRunListeners(Log log,            Collection<? extends SpringApplicationRunListener> listeners) {        this.log = log;        this.listeners = new ArrayList<SpringApplicationRunListener>(listeners);    }    public void started() {        for (SpringApplicationRunListener listener : this.listeners) {            listener.started();        }    }    public void environmentPrepared(ConfigurableEnvironment environment) {        for (SpringApplicationRunListener listener : this.listeners) {            listener.environmentPrepared(environment);        }    }

事件发布采用观察者模式

SpringBoot 之事件发布系统