如果我们想在项目启动后做一些事情(如加载定时任务,初始化工作),可以使用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:

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

被折叠的 条评论
为什么被折叠?



