Springboot 应用程序启动后执行的操作

本文介绍如何在SpringBoot应用启动后执行特定任务,通过实现CommandLineRunner或ApplicationRunner接口。文章详细解释了这两个接口的区别,前者提供对命令行参数的访问,后者使用ApplicationArguments接口。此外,还展示了如何通过实现Ordered接口或使用@Order注解来定义多个任务的执行顺序。

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

        如果在SpringApplication启动后需要运行某些特定代码,则可以实现ApplicationRunner  CommandLineRunner接口。 两个接口以相同的方式工作,并提供单个run方法,该方法在SpringApplication.run(…​)完成之前调用。

        CommandLineRunner接口提供对应用程序参数的访问,作为简单的字符串数组,而ApplicationRunner使用前面讨论的ApplicationArguments接口。 以下示例显示了带有run 方法的CommandLineRunner :

import org.springframework.boot.*;import org.springframework.stereotype.*;
@Component
public class MyBean implements CommandLineRunner {

	public void run(String... args) {
		// Do something...
	}

}

        如果定义了必须以特定顺序调用的多个CommandLineRunner or ApplicationRunner beans,则还可以实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order解,如下代码所示:

import org.springframework.boot.*;import org.springframework.stereotype.*;

@Component
@Order(value = 0)
public class MyBean implements CommandLineRunner {

	public void run(String... args) {
		// Do something...
	}

}
@Component
@Order(value = 1)
public class MyBean2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // Do something ...
    }

}

注:@Order 的值越小优先级越高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值