SpringBoot 启动初始化类 学习总结

本文总结了SpringBoot启动时的初始化类使用,包括在pom.xml中添加依赖、ApplicationRunner和CommandLineRunner的使用,以及它们的执行顺序和源码加载顺序。重点讨论了如何通过@Order注解来控制初始化顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.添加pom.xml

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.0.RELEASE</version>
</parent>

<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	<java.version>1.8</java.version>
</properties>

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>

2. 初始化启动类

CommandLineRunner 与 ApplicationRunner 都是初始化任务类,两者的区别主要在参数上。CommandLineRunner 只能处理参数值,是一个字符串数组进行接收,ApplicationRunner 对参数进行了封装处理,可以通过参数名进行参数值获取。

ApplicationRunner 执行结果:

@Component
public class ApplicationRun implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {

        System.out.println("sourceArgs:: "+ Arrays.asList(args.getSourceArgs()));
        System.out.println("nonOptions::"+args.getNonOptionArgs());
        System.out.println("optionNames::"+args.getOptionNames());
        System.out.println("param::"+ args.getOptionValues("param"));
        System.out.println("name::"+ args.getOptionValues("name"));
        System.out.println("hello::"+ args.getOptionValues("hello"));
    }
}

 

 CommandLineRunner 执行结果:

@Component
public class AbRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("===========CommandLineRunner============");
        System.out.println(Arrays.asList(args));
        System.out.println("The Runner start to initialize ...");

    }
}

3.  初始化执行顺序

 ApplicationRunner 优先于CommandLineRunner 加载,如果需要指定加载顺序,使用注解@Order(1) 

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {
    int value() default 2147483647;
}

 Order 默认按照从小到大的顺序进行加载

执行顺序结果: 

4. 源码加载顺序

总结:当需要在系统启动时,进行初始化工作时,可以使用ApplicationRunner 或CommandLineRunner进行,侧重点是对参数处理不一样。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值