SpringBoot(十四):CommandLineRunner-初始化资源

栏目: Java · 发布时间: 6年前

内容简介:个人博客:https://aodeng.cc微信公众号:低调小熊猫QQ群:756796932

个人博客:https://aodeng.cc

微信公众号:低调小熊猫

QQ群:756796932

简介

CommandLineRunner接口的Component会在spring bean初始化之后,SpringApplication run之前执行,可以控制在项目启动前初始化资源文件,比如初始化线程池,提前加载好加密证书等

实现接口(CommandLineRunner)

@order 表示加载顺序,-1,1,2,按照最小先执行的规则

Run类

@Component
@Order(-1)
public class Run implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("Run");
    }
}

我们多创建几个类实现接口

Run2类

@Component
public class Run2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("Run2");
    }
}

Run3类

@Component
@Order(1)
public class Run3 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Run3");
    }
}

启动程序

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        System.out.println("----------start--------");
        SpringApplication.run(Application.class,args);
        System.out.println("----------end--------");
    }
}

运行效果

(输出在start和end之间,说明CommandLineRunner 的执行时机,是在所有 Spring Beans 都初始化之后,SpringApplication.run() 之前执行,Run,Run3,Run2执行的顺序也是我们 @order 注解的顺序了)

----------start--------
Run
Run3
Run2
----------end--------

就是学习习惯做笔记了,这样印象深刻点,不论你在哪里看到我的文章,对你有帮助就好。下面是我放在

Github的源码: https://github.com/java-aodeng/hope


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms of the Intelligent Web

Algorithms of the Intelligent Web

Haralambos Marmanis、Dmitry Babenko / Manning Publications / 2009-7-8 / GBP 28.99

Web 2.0 applications provide a rich user experience, but the parts you can't see are just as important-and impressive. They use powerful techniques to process information intelligently and offer featu......一起来看看 《Algorithms of the Intelligent Web》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具