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

[SpringBoot]springboot -项目启动完成之后,执行特定方法

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

[SpringBoot]springboot -项目启动完成之后,执行特定方法

有时候项目会有这样的需求:在 springboot 项目启动完成之后,需要加载一些数据

最先想到的方法就是通过 ApplicationRunner 去做:

@Component
public class TestApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("TestApplicationRunner method will be execute when the project started");
    }
}

除了 ApplicationRunner 这种方式去做之外,还可以通过 CommandLineRunner 去做:

@Component
public class TestCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("TestCommandLineRunner method will be execute when the project started");
    }
}

上图是写了之后的运行效果图,应该可以看到,在项目启动成功之后,我们在 ApplicationRunner 和 CommandLineRunner 中的内容就运行了,而且执行顺序上, ApplicationRunner 要比 CommandLineRunner 先执行

这篇文章就先简单介绍一下 springboot 项目启动完成之后,如何执行特定方法,我在项目中用的第一种方式去实现的
如果想要让多个方法按照顺序执行,可以试下 @Order 实现方式:

@Component
public class TestApplicationRunnerByOrder implements ApplicationRunner, Ordered {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("TestApplicationRunnerByOrder method will be execute when the project started");
    }

    @Override
    public int getOrder() {
        // 通过设置这里的数字来指定执行顺序
        return 0;
    }
}


@Component
public class TestApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("TestApplicationRunner method will be execute when the project started");
    }
}

如果是上面的代码的话,运行之后,程序执行结果是这样的:

如果我们在 TestApplicationRunner 方法上,加上 @Order(value = 0) 注解:

@Component
@Order(value = 0)
public class TestApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("TestApplicationRunner method will be execute when the project started");
    }
}

接下来运行,就能看到执行顺序相比于刚刚,发生了变化:

以上,感谢您的阅读哇~

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

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

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