springboot 控制台输出调试

控制台输出调试

为了方便测试,在启动 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;
    }
}

执行结果为

  1. main before run
  2. second args[0]: param1
  3. second CommandLineRunner.run()
  4. first args[0]: param1
  5. first CommandLineRunner.run()
  6. third args[0]: param1
  7. third CommandLineRunner.run()
  8. main after run

    ApplicationRunner

    ApplicationRunner 接口和 CommandLineRunner 功能用法一致,唯一不同是对 args 参数进行了封装,run 方法传递参数为 ApplicationArguments,可以通过ApplicationArguments.getSourceArgs()获取字符数组参数 args。