目的: 平常开发中有可能需要实现在项目启动后执行的自定义的一些功能,实现自定义初始化任务。
一、CommandLineRunner
示例代码如下:
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* @author qinxun
* @date 2023-06-16
* @Descripion: CommandLineRunner方式
*/
@Component
@Order(1)
public class MyCommandLine1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 项目启动后会执行 我们可以在这里执行自定义的一些处理
System.out.println("MyCommandLine1运行");
}
}
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* @author qinxun
* @date 2023-06-16
* @Descripion: CommandLineRunner方式
*/
@Component
@Order(2)
public class MyCommandLine2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("MyCommandLine2运行");
}
}
@Component 注解将这个类注入到Spring容器中,接受Spring容器的管理。
@Order注解,表示启动任务的执行优先级,比如有多个类都实现CommandLineRunner,这个时候就可以加上这个注解设置执行的优先级,数字越小,优先级越大,越先执行。
run方法中写启动任务的逻辑,当项目启动时,run方法会被执行。run方法的参数,来自项目的启动参数。
我们启动项目,在控制台上可以看到在这个方法打印的数据。
二、ApplicationRunner
示例代码如下:
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
/**
* @author qinxun
* @date 2023-06-16
* @Descripion: ApplicationRunner方式
*/
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
// 项目启动后会执行 我们可以在这里执行自定义的一些处理
System.out.println("MyApplicationRunner运行");
}
}
我们启动项目,在控制台上可以看到在run方法打印的数据。
三、区别
CommandLineRunner的参数是String...args,传递的是字符串,run方法里直接获取传递的字符串。
ApplicationRunner的参数是ApplicationArguments,对参数进行了封装。