现在有一个非web项目: 比如一个kafka的消费端, 监听某个消息topic, 并处理对应的消息通过其他api发送通知或者短信给相关人员. 这时候想使用Spring Boot运行, 但又不需要依赖web, tomcat, jdbc这些

依赖如下:

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter</artifactId>
 <exclusions>
  <exclusion>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-to-slf4j</artifactId>
  </exclusion>
  <exclusion>
   <groupId>org.slf4j</groupId>
   <artifactId>jul-to-slf4j</artifactId>
  </exclusion>
 </exclusions>
</dependency>
<dependency>
 <groupId>org.springframework.kafka</groupId>
 <artifactId>spring-kafka</artifactId>
</dependency>

这时候 SpringBootApplication 的程序入口在执行完main方法后直接exit了, 现在需要hold应用程序防止直接退出, 有两种方法:

  • 实现 CommandLineRunner 接口在run方法中通过 Thread.currentThread().join() 使得应用程序在执行run方法时阻塞, 这样程序就可以保持运行
  • 通过 Spring Boot 提供的配置(推荐):
    • Spring Boot 2.0.0 以上的版本: spring.main.web-application-type=NONE // REACTIVE, SERVLET
    • Spring Boot 2.0.0 之前的版本: spring.main.web-environment=false

参考:

  1. SpringBoot 非 Web 项目运行
  2. Spring Boot without the web server

总结