SpringBoot 非 Web 项目运行

有时候一些项目并不需要提供 Web 服务,例如跑定时任务的项目,如果都按照 Web 项目启动未免画蛇添足浪费资源

为了达到非 Web 运行的效果,首先调整 Maven 依赖,不再依赖 spring-boot-starter-web,转而依赖最基础的 spring-boot-starter:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
</dependencies>

此时按照原先的方式启动 SpringBootApplication 会发现启动加载完之后会立即退出,这时需要做点工作让主线程阻塞让程序不退出:

1
2
3
4
5
6
7
8
9
10
11
12
@SpringBootApplication
public class SampleApplication implements CommandLineRunner {
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
Thread.currentThread().join();
}
}

这里利用了 SpringBoot 提供的 CommandLineRunner 特性,这个名字比较有欺骗性,实际效果如下:

SpringBoot 应用程序在启动后,会遍历 CommandLineRunner 接口的实例并运行它们的 run 方法。也可以利用 @Order 注解(或者实现Order接口)来规定所有 CommandLineRunner 实例的运行顺序

显示 Gitment 评论