spring boot 加载执行操作 Spring Boot容器加载时执行特定操作(推荐)

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring boot 加载执行操作 Spring Boot容器加载时执行特定操作(推荐)

林塬   2021-03-28 我要评论
想了解Spring Boot容器加载时执行特定操作(推荐)的相关内容吗,林塬在本文为您仔细讲解spring boot 加载执行操作的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:spring,boot,加载,下面大家一起来学习吧。

某些情况下我们需要在 Spring Boot 容器启动加载完后执行一些操作,此时可以通过实现 ApplicationListener<E extends ApplicationEvent> 接口,并指定相应事件来执行操作,例如启动某些自定义守护线程

ApplicationContextEvent 是由 ApplicationContext 引发的事件基类,它有几个实现类:

ContextRefreshedEvent :ApplicationContext 容器初始化或者刷新时触发该事件,执行一次
ContextStartedEvent :当使用 ConfigurableApplicationContext 接口的 start() 方法启动 ApplicationContext 容器时触发该事件
ContextClosedEvent :当使用 ConfigurableApplicationContext 接口的 close() 方法关闭 ApplicationContext 容器时触发该事件
ContextStopedEvent : 当使用 ConfigurableApplicationContext 接口的 stop() 方法停止 ApplicationContext 容器时触发该事件

代码例子

@Component
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
 @Override
 public void onApplicationEvent(ContextRefreshedEvent event) {
  System.out.println("容器初始化或者刷新时触发该事件,执行一次");
 }
}

总结

以上所述是小编给大家介绍的Spring Boot容器加载时执行特定操作,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们