springboot 控制台输出调试

控制台输出调试

为了方便测试,在启动springboot项目后,期望通过控制台输出,查看运行。
此时可以通过让**@SpringBootApplication类implements CommandLineRunner或者ApplicationRunner**接口,并实现run方法。

CommandLineRunner

CommandLineRunner接口的run方法会传递SpringApplication.run()方法中的字符数组参数args。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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。