Spring Boot应用启动后立即关闭的原因及解决办法

Spring Boot应用启动后立即关闭的原因及解决办法

技术背景

在开发Spring Boot应用时,有时会遇到应用启动后立即关闭的问题。这会导致无法正常提供服务,影响开发和测试进度。了解可能的原因并掌握相应的解决办法,对于顺利开发Spring Boot应用至关重要。

实现步骤

1. 检查依赖

确保项目中包含spring-boot-starter-web依赖。如果使用Maven,在pom.xml中添加以下内容:

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

如果使用Gradle,在build.gradle中添加:

1
2
3
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}

2. 检查嵌入式容器

若使用了嵌入式容器(如Tomcat),要保证其配置正确。有时移除不必要的嵌入式容器依赖可能会解决问题。例如,移除以下依赖:

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>

3. 检查application.properties文件

检查是否存在spring.main.web-application-type=none这一行,若有则注释或删除它。

4. 检查代码逻辑

确保代码中没有意外关闭应用上下文的逻辑。例如,避免在main方法中调用close()方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 错误示例
@SpringBootApplication
public class SpringBootApacheKafkaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApacheKafkaApplication.class, args).close();
}
}

// 正确示例
@SpringBootApplication
public class SpringBootApacheKafkaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApacheKafkaApplication.class, args);
}
}

5. 检查循环依赖

确保不存在循环依赖问题。例如,Class A注入Class B,而Class B又注入Class A

6. 检查运行环境

如果在Kubernetes等环境中运行,要确保端口配置正确,避免因存活探针失败导致应用被关闭。

核心代码

以下是一个简单的Spring Boot应用示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class SampleController {

@GetMapping("/")
public String home() {
return "Hello World!";
}

public static void main(String[] args) {
SpringApplication.run(SampleController.class, args);
}
}

最佳实践

  • 使用官方工具生成项目:使用start.spring.io生成项目,确保pom.xmlbuild.gradle文件的初始配置正确。
  • 及时更新依赖:保持依赖库的更新,避免使用过时的版本。
  • 详细日志记录:在开发和调试阶段,开启详细的日志记录,方便定位问题。

常见问题

1. 添加spring-boot-starter-web依赖后仍未解决问题

可能是嵌入式容器的JAR文件损坏。可以运行Maven构建的调试模式:

1
mvn spring-boot:run --debug

若发现类似invalid LOC header (bad signature)的错误信息,可清除本地Maven仓库:

1
mvn dependency:purge-local-repository

2. 在IDE中运行正常,但部署到Kubernetes后立即关闭

检查应用的端口配置是否与Kubernetes的配置一致,确保存活探针配置正确。

3. 移除spring-boot-starter-tomcat依赖后应用无法启动

可尝试替换为其他嵌入式容器依赖,如:

1
2
3
4
5
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.6</version>
</dependency>

Spring Boot应用启动后立即关闭的原因及解决办法
https://119291.xyz/posts/2025-04-28.spring-boot-app-startup-shutdown-issue/
作者
ww
发布于
2025年4月28日
许可协议