栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot在项目启动之后执行特定任务的实现方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot在项目启动之后执行特定任务的实现方式

文章目录
      • 场景
      • 解决

场景
  • 项目经常需要在启动之后完成一些初始化的工作,在整个项目周期只执行一次
解决
  1. 通过监听ApplicationReadyEvent事件实现

  2. 实现CommandLineRunner接口, 在项目启动之后执行run方法,并传递用于启动应用程序的命令行参数 具体操作如下

@Component 注册为bean
@Order控制启动顺序,但是不建议使用,顺序意味着有前后依赖,不安全
run方法有抛出异常,Spring Boot 会将 CommandLineRunner 作为应用启动的一部分,如果运行 run() 方法时抛出 Exception,应用将会终止启动 (这会导致DisposableBean触发)

@Component
@Order(3)
@Slf4j
public class MyCommandLineRunner2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.info("MyCommandLineRunner2 is running and order is 3");
    }
}

@Component
@Slf4j
@Order(2)
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.info("MyCommandLineRunner is running and order is 2");
    }
}

  1. ApplicationRunner 和CommandLineRunner基本相同,只是对命令行参数的处理不同,ApplicationRunner会对参数解析
@Component
@Order(4)
@Slf4j
public class MyApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
       log.info("MyApplicationRunner is running and order is 4");
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/885837.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号