Spring Boot非Web项目如何启动运行?
- 内容介绍
- 文章标签
- 相关推荐
本文共计444个文字,预计阅读时间需要2分钟。
有时一些项目不需要提供Web服务,例如跑定时任务的项目。如果都按照Web项目启动,则可能免不了画蛇添足,额外增加不必要的资源消耗。为了达到非Web运行的效果,首先调整Maven依赖,不再依赖spring-boot。
有时候一些项目并不需要提供 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 实例的运行顺序
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对自由互联的支持。
本文共计444个文字,预计阅读时间需要2分钟。
有时一些项目不需要提供Web服务,例如跑定时任务的项目。如果都按照Web项目启动,则可能免不了画蛇添足,额外增加不必要的资源消耗。为了达到非Web运行的效果,首先调整Maven依赖,不再依赖spring-boot。
有时候一些项目并不需要提供 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 实例的运行顺序
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对自由互联的支持。

