Spring Boot启动创建requestMappingHandlerAdapter失败问题排查
问题原因与解决方案
错误产生原因
核心原因是@RequestParam是Spring Web模块提供的Controller层请求参数绑定注解,仅可用于Controller类的接口方法参数上,不能作用于Spring Data JPA的Repository接口方法参数。
你在Repository的findByCategoryId方法参数上添加@RequestParam后,Spring启动初始化Web层核心组件requestMappingHandlerAdapter时,会扫描所有携带请求参数注解的方法,识别到Repository层的非法注解后解析失败,最终抛出Bean创建异常。
解决办法
- 移除
ProductRepository接口中findByCategoryId方法参数上的@RequestParam注解,Spring Data JPA会自动根据方法名规则匹配参数和实体类对应属性,无需额外注解。
修正后的Repository代码示例:public interface ProductRepository extends JpaRepository<Product, Long> { Page<Product> findByCategoryId(Long categoryId, Pageable pageable); } - 若需要接收前端传递的分类ID和分页参数,将
@RequestParam注解加到对应Controller层方法的参数上,调用Repository时直接传入参数即可,示例代码:@RestController @RequestMapping("/product") public class ProductController { @Autowired private ProductRepository productRepository; @GetMapping("/listByCategory") public Page<Product> getProductListByCategory(@RequestParam Long categoryId, Pageable pageable) { return productRepository.findByCategoryId(categoryId, pageable); } } - 修正完成后重启项目即可解决该启动异常。
内容的提问来源于stack exchange,提问作者Gautam Kumar
相关产品推荐
相关产品推荐

