软件编程
位置:首页>> 软件编程>> java编程>> Spring Boot非Web项目运行的方法

Spring Boot非Web项目运行的方法

作者:Sunshow  发布时间:2021-07-23 13:05:32 

标签: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 会发现启动加载完之后会立即退出,这时需要做点工作让主线程阻塞让程序不退出:


@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 实例的运行顺序

来源:https://sunshow.net/2017/01/06/springboot-non-web-project/

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com