Spring项目启动时,如果需要初始化资源,可以实现ApplicationRunner或者CommandLineRunner,并且可以使用注解@Order指定他们的运行顺序。


示例代码:https://github.com/rickding/HelloJava/tree/master/HelloRunner

3个类文件:

Spring项目启动时,ApplicationRunner和CommandLineRunner的用法_第1张图片


RunnerApplication.java实现SpringBootApplication主程序:

Spring项目启动时,ApplicationRunner和CommandLineRunner的用法_第2张图片


HelloApplicationRunner.java实现ApplicationRunner:

Spring项目启动时,ApplicationRunner和CommandLineRunner的用法_第3张图片


HelloCommandLineRunner.java实现CommandLineRunner,并且指定@Order(1):

Spring项目启动时,ApplicationRunner和CommandLineRunner的用法_第4张图片


输出日志:

Spring项目启动时,ApplicationRunner和CommandLineRunner的用法_第5张图片


参考文章:https://blog.csdn.net/qq_28804275/article/details/80891941