Spring Boot启动过程中相关事件

  • Spring容器创建前:

  1. ApplicationStartingEvent: Spring容器创建前,项目启动时执行;
  2. ApplicationEnvironmentPreparedEvent: Spring容器创建前,yml等配置文件加载后执行;
  • Spring容器创建后:

  1. ApplicationPreparedEvent: Spring容器创建后,Bean创建前执行;
  2. ContextRefreshedEvent: Spring容器创建后,Bean创建后执行;
  3. ApplicationStartedEvent: Spring Boot项目启动成功执行;

知识点: 前三种事件发布时, 因为Spring容器还未创建, 所以不能直接使用Spring事件监听器的方式。 需要使用Spring Boot加载事件监听器的方式;

步骤: 

  1. 创建spring.factories文件; resource --> META-INF --> spring.factories
  2. 自定义事件监听器:
  3. public class MyApplicationListener implements ApplicationListener{
    
        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            //todo... 做幂等校验,防止业务多次执行;
            if (event instanceof ApplicationStartingEvent) {
                System.out.println("Spring容器创建前,项目启动时, 执行==========================");
                System.out.println("不可以使用Spring容器中的Bean");
            } else if (event instanceof ApplicationEnvironmentPreparedEvent) {
                System.out.println("Spring容器创建前,yml等配置文件加载后, 执行==================");
                System.out.println("不可以使用Spring容器中的Bean");
            } else if (event instanceof ApplicationPreparedEvent) {
                System.out.println("Spring容器创建后,Bean创建前, 执行==========================");
                System.out.println("不可以使用Spring容器中的Bean");
            } else if (event instanceof ContextRefreshedEvent) {
                System.out.println("Spring容器创建后,Bean创建后, 执行==========================");
                System.out.println("可以使用Spring容器中的Bean");
            } else if (event instanceof ApplicationStartedEvent) {
                System.out.println("Spring Boot项目启动成功, 执行==============================");
                System.out.println("可以使用Spring容器中的Bean");
            }
        }
    }
  4. 将自定义监听器加入spring.factories文件中: 
    org.springframework.context.ApplicationListener=
    \com.example.springbootdemo.listener.MyApplicationListener
  5. 完成;

启动日志:

 

特别注意: 

     需要在onApplicationEvent()方法中,做幂等校验(业务执行前);原因如下两点:

  1. 服务可能会多节点部署;
  2. 因为集成Spring Cloud时,run()方法会被执行两次;所以如果项目中集成了Spring Cloud,则事件也会被触发两次;

     例如: 使用redis的setnx命令做幂等校验等;

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值