🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
CommandLineRunner 接口可以实现当服务启动时预先加载一些功能,比如参数预先加载等。当需要实现多个功能预先加载时,需要使用`@Order`来指定加载的顺序。 ```java public @interface Order { int value() default 2147483647; //该值越小,越先被执行 } ``` 使用步骤如下: **1. 创建SpringBoot项目** **2. 创建三个类来实现CommandLineRunner接口** (1)CommandLineRunnerDriver1。 ```java import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(value = 1) public class CommandLineRunnerDriver1 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("CommandLineRunnerDriver1执行成功!"); } } ``` (2)CommandLineRunnerDriver2。 ```java import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(value = 2) public class CommandLineRunnerDriver2 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("CommandLineRunnerDriver2执行成功!"); } } ``` (3)CommandLineRunnerDriver3。 ```java import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(value = 3) public class CommandLineRunnerDriver3 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("CommandLineRunnerDriver3执行成功!"); } } ``` **3. 运行启动类,预加载的顺序如下** ``` CommandL ineRunnerDriver1执行成功! CommandL ineRunnerDriver2执行成功! CommandL ineRunnerDriver3执行成功! ```