现在的位置: 首页 > 编程语言 > 正文

SpringBoot非Web项目运行的方法

2020年02月13日 编程语言 ⁄ 共 925字 ⁄ 字号 评论关闭

有时候一些项目并不需要提供 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 会发现启动加载完之后会立即退出,这时需要做点工作让主线程阻塞让程序不退出:

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。

本文标题: Spring Boot非Web项目运行的方法

以上就上有关SpringBoot非Web项目运行的方法的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.