SpringBoot-4.SmartLifecycle分析

SmartLifecycle是一个扩展了Lifecycle接口,可以跟踪spring容器ApplicationContext刷新或者关闭的接口,实现该接口的实现类有特定的执行顺序。

当ApplicationContext刷新时,所有bean都加载和初始化完成后,根据isAutoStartup和isRunning判断是否自动执行start()

1.新建TestSmartLifecycle类

public class TestSmartLifecycle implements SmartLifecycle {
   
  @Override
    public void start() {
        System.out.println("TestSmartLifecycle is start");
    }
//SmartLifecycle组件停止后的回调,程序被异步关闭
    @Override
    public void stop() {
        System.out.println("SmartLifecycle is stop");
    }
//为false,并且isAutoStartup为true,执行start方法
//为true,执行stop方法。
    @Override
    public boolean isRunning() {
        return false;
    }
//如果为true,实现了SmartLifecycle 接口的组件,能再ApplicationContext已经刷新的时候,自动执行start方法,
    @Override
    public boolean isAutoStartup() {
        return true;
    }
//当running为true时,再应用关闭时会执行stop(Runnable callback)方法,
如果再执行完stop后,running没有设置为false时,应用会卡住一段时间,无法退出
    @Override
    public void stop(Runnable callback) {
        System.out.println("TestSmartLifecycle is stop");
        callback.run();
    }

    @Override
    public int getPhase() {
        return 0;
    }
}

2.配置Bean

@Configuration
public class TestConfiguration {

    @Bean
    TestSmartLifecycle testSmartLifecycle(){
        return new TestSmartLifecycle();
    }
}

3.debugger启动应用程序

可以看见如下的调用链,大致是SpringApplication.run(CommonsTestApplication.class, args)-->refreshContext-->refresh-->startBeans-->start,其中,再startBean中获取了所有实现SmartLifecycle的非懒加载的bean,并再start方法中,调用对应实现bean的start方法,执行相应的逻辑,具体可看下面截图。

private void startBeans(boolean autoStartupOnly) {
		Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
		Map<Integer, LifecycleGroup> phases = new HashMap<>();
		lifecycleBeans.forEach((beanName, bean) -> {
			if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
				int phase = getPhase(bean);
				LifecycleGroup group = phases.get(phase);
				if (group == null) {
					group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
					phases.put(phase, group);
				}
				group.add(beanName, bean);
			}
		});
		if (!phases.isEmpty()) {
			List<Integer> keys = new ArrayList<>(phases.keySet());
			Collections.sort(keys);
			for (Integer key : keys) {
				phases.get(key).start();
			}
		}
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿孟呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值