You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3接口404求助:连接MySQL后端点失效

Spring Boot连接MySQL后端点404排查方案

问题描述

应用初期端点正常工作,连接MySQL后数据库功能正常,但所有端点(包括新增的/test)均返回404,访问地址为http://localhost:8081/test。

排查步骤

1. 修复依赖冲突

你的POM中手动引入了spring-webmvc 5.1.2.RELEASE,但spring-boot-starter-web已经包含了适配当前Spring Boot版本的webmvc依赖,手动指定低版本会导致Web MVC自动配置失效、请求映射无法注册。

解决方法:移除POM中以下依赖:

<!-- 移除该依赖,spring-boot-starter-web已包含适配版本的webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.2.RELEASE</version>
</dependency>

同时,jakarta.persistence-api 3.0.0可能和spring-boot-starter-data-jpa自带的JPA API版本冲突,建议移除该手动引入的依赖,避免版本不兼容。

2. 确认控制器包扫描范围

Spring Boot默认只扫描主应用启动类所在包及其子包下的组件。如果EmployeeController所在包不在主类的包层级内,控制器不会被Spring容器识别,端点无法注册。

解决方法:

  • 将EmployeeController移动到主应用类的包或其子包下
  • 或者在主应用类上添加@ComponentScan注解,指定控制器所在包路径:
@SpringBootApplication
@ComponentScan(basePackages = {"com.yourpackage.controller"}) // 替换为实际控制器包路径
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

3. 验证服务器端口配置

你访问的是8081端口,但Spring Boot默认端口为8080。需确认application.properties或application.yml中是否正确设置端口:

# 确认端口是否为8081
server.port=8081

若端口配置错误,访问8081会直接返回404。

4. 检查应用启动日志

查看应用启动日志,重点关注:

  • 是否有MappingHandlerMapping相关日志,确认/test和/employees端点是否被注册,示例日志:
    Mapped "{[/test],methods=[GET]}" onto public java.lang.String com.example.controller.EmployeeController.getResponseTest()
    
  • 是否存在Bean加载异常、数据库连接相关的警告/错误,即使数据库功能正常,启动时的异常也可能导致Web容器初始化不完全,无法处理请求。

5. 确认控制器注解正确性

检查EmployeeController的@RestController注解是否导入正确的包:

// 必须是Spring Web的官方注解
import org.springframework.web.bind.annotation.RestController;

若导入错误包,控制器不会被识别为请求处理类。


内容的提问来源于stack exchange,提问作者Randi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:48:10