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

Spring Boot应用GET请求不支持求助:已定义接口仍报405错误

解决Spring Boot控制器GET请求405 Method Not Allowed问题

兄弟,我一眼就瞅出问题所在了——你把@RestController的用法搞错啦!

你当前的控制器代码里,@RestController("/api/v1/profiles")这种写法完全不对:@RestController注解的value参数是用来定义Spring Bean的名称,不是用来指定请求的基础路径的。这就导致你的@GetMapping("/{id}")并没有挂载到/api/v1/profiles/{id}这个目标路径上,当你用PostMan请求这个地址时,Spring找不到对应的GET请求处理器,就返回了405错误(要么是有其他匹配到该路径但不支持GET的处理器,要么就是完全没匹配到有效处理器,Spring默认返回405)。

修复步骤

把控制器的注解改成下面这样,用@RequestMapping来指定基础请求路径:

@RestController
@RequestMapping("/api/v1/profiles") // 这里才是指定基础请求路径的正确位置
public class ProfileController {
    private ProfileService service;

    @Autowired
    public ProfileController(ProfileService service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity createProfile(
            @RequestBody ProfileDocument document) throws Exception {
        return new ResponseEntity(service.createProfile(document), HttpStatus.CREATED);
    }

    @GetMapping("/{id}")
    public ProfileDocument findById(@PathVariable String id) throws Exception {
        return service.findById(id);
    }
}

额外验证点

  1. 启动Spring Boot后,查看控制台日志,应该能看到类似这样的映射注册日志:o.s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/v1/profiles/{id}],methods=[GET]}",出现这条日志就说明路径映射已经正确注册
  2. 确认ProfileService.findById(id)方法本身能正常执行,不会抛出未捕获的异常
  3. 重新用PostMan请求GET /api/v1/profiles/464d06e8-ef57-49f3-ac17-bd51ba7786e2,应该就能正常返回数据了

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:09:59