Hello朋友们,我是RatelBlog的李某人。
很多时候我们在开发中会遇到这种场景,就是在项目启动后立刻执行某些自定义的代码。
比如:在项目启动后初始化加载数据、或者进行一些其它的业务操作。
SpringBoot提供了两个接口来帮助我们实现这种需求。这两个接口分别为CommandLineRunner
和ApplicationRunner。它们的执行时机是容器启动完成后。
@FunctionalInterface
public interface ApplicationRunner {
/**
* Callback used to run the bean.
* @param args incoming application arguments
* @throws Exception on error
*/
void run(ApplicationArguments args) throws Exception;
}
@FunctionalInterface
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;
}
二者的功能和官方文档一模一样,都是在容器初始化完毕之后执行起run方法
这两个接口的不同之处在于:ApplicationRunner中run方法的参数为ApplicationArguments,
而CommandLineRunner接口中run方法的参数为String数组。
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
public static final Logger logger = LoggerFactory.getLogger(ApplicationRunnerImpl.class.getName());
@Override
public void run(ApplicationArguments args) throws Exception {
logger.info("ApplicationRunner OK 项目启动后执行自定义程序如下。。。");
}
}
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
public static final Logger logger = LoggerFactory.getLogger(CommandLineRunnerImpl.class.getName());
@Override
public void run(String... args) throws Exception {
logger.info("CommandLineRunner OK 项目启动后执行自定义程序如下。。。");
}
}
...
Generating unique operation named: findRbUserListUsingGET_1
Started RatelblogApplication in 4.373 seconds (JVM running for 5.343)
ApplicationRunner OK 项目启动后执行自定义程序如下。。。
CommandLineRunner OK 项目启动后执行自定义程序如下。。。
如果我们有多个实现类,需要按照一定的顺序执行,那么可以通过@Order注解实现。
在实现类上加上@Order注解。@Order(value=整数值)。SpringBoot会按照@Order
中的value值从小到大依次执行。
@Order(value = 2)
@Component
public class ApplicationRunnerImpl implements ApplicationRunner{
...
...
}
@Order(value = 1)
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
...
...
}
...
Generating unique operation named: findRbUserListUsingGET_1
Started RatelblogApplication in 4.373 seconds (JVM running for 5.343)
CommandLineRunner OK 项目启动后执行自定义程序如下。。。
ApplicationRunner OK 项目启动后执行自定义程序如下。。