介绍
这篇文章主要介绍了弹簧引导如何实现非Web项目运行,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获、下面让小编带着大家一起了解一下。
有时候一些项目并不需要提供Web服务,例如跑定时任务的项目,如果都按照网络项目启动未免画蛇添足浪费资源
为了达到非Web运行的效果,首先调整Maven依赖,不再依赖spring-boot-starter-web,转而依赖最基础的spring-boot-starter:
& lt; dependencies> ,& lt; dependency> & lt;才能groupId> org.springframework.boot</groupId> & lt;才能artifactId> spring-boot-starter</artifactId> ,& lt;/dependency> & lt;/dependencies>
此时按照原先的方式启动SpringBootApplication会发现启动加载完之后会立即退出,这时需要做点工作让主线程阻塞让程序不退出:
@SpringBootApplication public class  SampleApplication implements CommandLineRunner  { ,public static  void main (String [], args), throws Exception { SpringApplication.run才能(SampleApplication.class, args); ,} ,@Override ,public void 运行(字符串…,args), throws Exception { Thread.currentThread才能(). join (); ,} }
这里利用了SpringBoot提供的CommandLineRunner特性,这个名字比较有欺骗性,实际效果如下:
SpringBoot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的运行方法。也可以利用@Order注解(或者实现订单接口)来规定所有CommandLineRunner实例的运行顺序
引用>弹簧引导如何实现非Web项目运行