启动系统任务
有一些特殊的任务需要在系统启动时执行,例如配置文件加载、数据库初始化等操作。如果没有使用Spring Boot,这些问题可以在Listener中解决。
Spring Boot对此提供了两种解决方案:CommandLineRunner和ApplicationRunner。CommandLineRunner和ApplicationRunner基本一致,差别主要体现在参数上。
CommandLineRunner
Spring Boot项目在启动时会遍历所有CommandLineRunner的实现类并调用其中的run方法,如果整个系统中有多个CommandLineRunner的实现类,那么可以使用@Order注解对这些实现类的调用顺序进行排序。在一个Spring Boot Web项目中添加两个CommandLineRunner,分别如下:
MyCommandLineRunner.java
package com.shrimpking.config;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/5 10:41
*/
@Component
@Order(1)
public class MyCommandLineRunner1 implements CommandLineRunner
{
@Override
public void run(String... args) throws Exception
{
System.out.println("Runner1>>>" + Arrays.toString(args));
}
}
MyCommandLineRunner2.java
package com.shrimpking.config;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/5 10:42
*/
@Component
@Order(2)
public class MyCommandLineRunner2 implements CommandLineRunner
{
@Override
public void run(String... args) throws Exception
{
System.out.println("Runner2>>>" + Arrays.toString(args));
}
}
代码解释:
• @Order(1)注解用来描述CommandLineRunner的执行顺序,数字越小越先执行。
• run方法中是调用的核心逻辑,参数是系统启动时传入的参数,即入口类中main方法的参数(在调用SpringApplication.run方法时被传入Spring Boot项目中)。
在系统启动时,配置传入的参数。以IntelliJ IDEA为例,配置方式如下: