为何springboot启动类实现了CommandLineRunner.run()后需要创建新的线程
1.先写个controller类方便请求测试
http://localhost:8080/test/getRequest
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("getRequest")
public String enums() {
System.out.println("收到请求...");
return "success";
}
}
2.在启动类实现CommandLineRunner接口,此时没有创建新的线程,直接重写了CommandLineRunner中的run()方法.
public class Demo01Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Demo01Application.class, args);
}
@Override
public void run(String... args) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2s..... i = " + i);
if (i == 3) throw new RuntimeException("i == 3 runtimeException...");
}
}
}
启动测试…
如图显示,此时项目日志显示启动失败
尝试访问
并不行…
---------------分割线-----------------
此时采用创建线程方式再次测试…
public class Demo01Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Demo01Application.class, args);
}
@Override
public void run(String... args) {
new Thread() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2s..... i = " + i);
if (i == 3) throw new RuntimeException("i == 3 runtimeException...");
}
}
}.start();
}
}
如图显示启动成功…
再次尝试访问
访问成功
这是因为如果不采用创建线程的方式实现CommandLineRunner的run()方法.项目主线程需要等待CommandLineRunner.run()成功执行完成之后才能完成真正的启动.如果此时CommandLineRunner.run()报错.将导致整个项目启动失败.
采用创建线程的方式启动即使报错了,也是这个单个线程报错.不影响整个项目的启动
所以,当实现了CommandLineRunner.run()方法一定要创建新的线程,然后从中写逻辑