CommandLineRunner、ApplicationRunner 接口

本文介绍了Spring中用于项目启动后执行任务的CommandLineRunner和ApplicationRunner接口。这两个接口允许在容器启动成功后进行回调操作,例如加载定时任务或初始化工作。CommandLineRunner接口的执行顺序由order注解决定,而ApplicationRunner接口接收封装后的ApplicationArguments参数,便于直接通过参数名获取值。需要注意的是,执行方法内必须捕获异常,以免影响项目启动。

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

       如果我们想在项目启动后做一些事情(如加载定时任务,初始化工作),可以使用spring提供的CommandLineRunner、ApplicationRunner 接口,在容器启动成功后的最后一步回调(类似开机自启动)。

1. CommandLineRunner接口

/**
 * Interface used to indicate that a bean should <em>run</em> when it is contained within
 * a {@link SpringApplication}. Multiple {@link CommandLineRunner} beans can be defined
 * within the same application context and can be ordered using the {@link Ordered}
 * interface or {@link Order @Order} annotation.
 * <p>
 * If you need access to {@link ApplicationArguments} instead of the raw String array
 * consider using {@link ApplicationRunner}.
 *
 * @author Dave Syer
 * @see ApplicationRunner
 */
public interface CommandLineRunner {
   

	/**
	 * Callback used to run the bean.
	 * @param args incoming main method arguments
	 * @throws Exception on error
	 */
	void run(String... args) throws Exception;

}

多个CommandLineRunner可以被同时执行在同一个spring上下文中并且执行顺序是以order注解的参数顺序一致。

下面看一个demo:


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值