控制台输出调试
为了方便测试,在启动 springboot 项目后,期望通过控制台输出,查看运行。
此时可以通过让**@SpringBootApplication 类 implements CommandLineRunner 或者ApplicationRunner**接口,并实现 run 方法。
CommandLineRunner
CommandLineRunner 接口的 run 方法会传递 SpringApplication.run()方法中的字符数组参数 args。
@SpringBootApplication public class Main implements CommandLineRunner { public static void main(String[] args) { System.out.println("main before run"); SpringApplication.run(Main.class, "param1"); System.out.println("main after run"); } public void run(String... args) throws Exception { System.out.println("args[0]: " + args[0]); System.out.println("CommandLineRunner.run()"); } }
如果有多个 @SpringBootApplication 注解类且均实现了 CommandLineRunner 接口,可以通过**@Order 注解指定 run 方法的执行顺序,或者通过实现 Ordered 接口的 getOrder()**方法。
qQ320491
package crick.wang.springbootstudy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; @SpringBootApplication @Order(2) public class Main implements CommandLineRunner { public static void main(String[] args) { System.out.println("main before run"); SpringApplication.run(Main.class, "param1"); System.out.println("main after run"); } public void run(String... args) throws Exception { System.out.println("first args[0]: " + args[0]); System.out.println("first CommandLineRunner.run()"); } } @SpringBootApplication @Order(1) class SecondMain implements CommandLineRunner { public void run(String... args) throws Exception { System.out.println("second args[0]: " + args[0]); System.out.println("second CommandLineRunner.run()"); } } @SpringBootApplication class ThirdMain implements CommandLineRunner, Ordered { public void run(String... args) throws Exception { System.out.println("third args[0]: " + args[0]); System.out.println("third CommandLineRunner.run()"); } public int getOrder() { return 3; } }
执行结果为
- main before run
- second args[0]: param1
- second CommandLineRunner.run()
- first args[0]: param1
- first CommandLineRunner.run()
- third args[0]: param1
- third CommandLineRunner.run()
- main after run
ApplicationRunner
ApplicationRunner 接口和 CommandLineRunner 功能用法一致,唯一不同是对 args 参数进行了封装,run 方法传递参数为 ApplicationArguments,可以通过**ApplicationArguments.getSourceArgs()**获取字符数组参数 args。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于