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

Spring整合MongoDB时RestController报错No adapter for handler如何解决?

错误原因与解决方案

核心错误:@RestController注解使用错误

@RestController 注解的value属性作用是指定该Controller在Spring容器中的Bean名称,不是设置接口的公共路径前缀。你写的@RestController("/products")相当于把这个Controller的Bean命名为/products,没有实际配置路径映射,导致Spring MVC无法将请求和处理方法绑定,因此抛出找不到HandlerAdapter的错误。

修正方法:

把Controller的注解改为组合使用@RestController + @RequestMapping来配置公共路径前缀:

// 错误写法
// @RestController("/products")
// 正确写法
@RestController
@RequestMapping("/products")
@AllArgsConstructor
public class productRestController {
    // 原有方法逻辑不变
}

修改后方法上的@GetMapping("/")对应的实际路径就是/products/,和你调用的路径完全匹配。


其他需要修正的潜在问题

1. 路径冲突问题

你当前写的两个查询接口路径完全一致:

@GetMapping("/products/{name}")
public Product getProductsByName(@PathVariable("name")Optional<String> name )

@GetMapping("/products/{price}")
public List<Product> getProductsByPrice(@PathVariable("price")Optional<Integer> price )

Spring MVC无法通过路径变量的类型区分路由,调用时会直接报错。需要修改为不同的路径,同时注意类上已经配置了/products前缀,方法上不需要重复写:

// 实际路径为 /products/name/xxx
@GetMapping("/name/{name}")
public Product getProductsByName(@PathVariable("name") String name )

// 实际路径为 /products/price/xxx
@GetMapping("/price/{price}")
public List<Product> getProductsByPrice(@PathVariable("price") Integer price )

如果参数是必填项,不需要用Optional接收,直接使用对应类型即可;如果是非必填,需要额外配置@PathVariable(required = false)。

2. 编码规范问题

Java的类、接口名称要求使用大驼峰命名法,你当前的productRepository、productServiceImpl、productRestController都不符合规范,建议修改为ProductRepository、ProductServiceImpl、ProductRestController,避免后续引发其他潜在的Bean注入、组件扫描问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:54:05