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

Spring Boot 3.2接口调用返回404:@SpringBootApplication无法扫描控制器

Spring Boot 3.2 接口404:控制器扫描失败排查方案

问题场景

  • 开发环境:Spring Boot 3.2 + IntelliJ IDEA
  • 现象:调用/api/users接口返回404,推测@SpringBootApplication未扫描到UserController
  • 已尝试操作:配置@SpringBootApplication(scanBasePackages = {"com.other.packages","com.other"}),问题未解决

相关代码

启动类代码:

@SpringBootApplication
public class TaskManagementApplication {

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

控制器代码:

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
}

排查与解决步骤

1. 核对包结构匹配规则

Spring Boot默认扫描启动类所在包及其所有子包下的组件。比如启动类TaskManagementApplication如果在com.example.taskmanagement包下,UserController必须放在com.example.taskmanagement或其子包(如com.example.taskmanagement.controller)内,否则默认扫描不到。

2. 修正scanBasePackages配置

如果控制器不在启动类的包路径下,必须指定实际存在的控制器所在包,不能写错误的包名。例如控制器在com.example.taskmanagement.controller,配置应为:

@SpringBootApplication(scanBasePackages = "com.example.taskmanagement")
// 或者精准指定控制器所在子包
@SpringBootApplication(scanBasePackages = "com.example.taskmanagement.controller")

3. 给控制器添加有效请求方法

当前UserController仅配置了类级别的@RequestMapping("/api/users"),但没有具体的请求处理方法(如@GetMapping、@PostMapping),即使扫描成功,访问接口也会返回404。添加测试方法验证:

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public String testController() {
        return "User controller is accessible!";
    }
}

4. 清理项目缓存并重建

在IntelliJ IDEA中执行:

  • Build → Clean Project
  • Build → Rebuild Project
    编译缓存可能导致组件扫描异常,清理后重建可解决此类问题。

5. 检查启动日志验证扫描结果

启动项目时,查看控制台日志,搜索包含Mapped "{[/api/users...]"的日志条目。如果能找到,说明控制器已成功扫描并映射;如果找不到,需重新检查包结构和scanBasePackages配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:32:28