前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot扩展机制: SpringApplicationRunListener

Spring Boot扩展机制: SpringApplicationRunListener

作者头像
十毛
发布2021-06-21 18:21:56
1K0
发布2021-06-21 18:21:56
举报
文章被收录于专栏:用户1337634的专栏

Spring Boot引入了一个新的扩展接口SpringApplicationRunListener,可以监听Spring Application启动过程的各个阶段,比如应用开始启动、环境ready、上下文ready等

自定义扩展类

  • TenmaoRunListener 需要注意的就是构造函数,比如接受两个参数SpringApplication application, String[] args。这一点也蛮有意思,为什么扩展机制还需要有一些潜规则呢?是不是接口上实现这两个参数的赋值是不是更好一些?
代码语言:javascript
复制
@Slf4j
public class TenmaoRunListener implements SpringApplicationRunListener {
    public TenmaoRunListener(SpringApplication application, String[] args) {
        log.info("TenmaoRunListener Constructor: application[{}] args: {}",
                application.getMainApplicationClass(), Arrays.toString(args));
    }

    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        log.info("starting");
    }

    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        log.info("environmentPrepared");
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        log.info("contextPrepared");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        log.info("contextLoaded");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        log.info("started");
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
        log.info("running");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        log.info("failed");
    }
}

启动方式:resources/META-INF/spring.factories

代码语言:javascript
复制
org.springframework.boot.SpringApplicationRunListener=com.tenmao.initializer.TenmaoRunListener

作用

  • 这个扩展机制作用目前来看并不是很大,主要用来做一些事件发布或通知。在Spring Boot内部,目前也只有EventPublishingRunListener使用了这个扩展接口

疑问

  • 为什么Spring没有使用事件机制,而是使用各种监听器呢? 一种猜测,就是事件机制不方便携带太多不同的参数
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 自定义扩展类
  • 启动方式:resources/META-INF/spring.factories
  • 作用
  • 疑问
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档