异常:Expected lookupPath in request attribute “org.springframework.web.util.UrlPathHelper.PATH“

Spring Boot 2.x 动态注册 RequestMapping 路径匹配异常解决方案

Expected lookupPath in request attribute "org.springframework.web.util.UrlPathHelper.PATH"

问题描述

异常信息:

java.lang.IllegalArgumentException: Expected lookupPath in request attribute "org.springframework.web.util.UrlPathHelper.PATH"

问题原因

此错误出现在 Spring Boot 2.x 中动态构造 RequestMappingInfo 的场景:

  • 使用 RequestMappingInfo.Builder 动态注册端点
  • RequestMappingInfo.BuilderConfiguration 未正确配置
  • Spring Boot 2.x 中 BuilderConfiguration 默认没有设置 PatternParser

核心问题:

  • Spring Boot 2.x 的 RequestMappingHandlerMapping 依赖 UrlPathHelper 解析路径
  • 动态注册时未正确初始化路径解析所需的配置
  • 请求处理时无法从 request attribute 中获取 lookupPath

解决方案

核心解决代码:

RequestMappingInfo.BuilderConfiguration options = new RequestMappingInfo.BuilderConfiguration();
options.setPatternParser(new PathPatternParser());

RequestMappingInfo.Builder builder = RequestMappingInfo
    .paths(definition.getPath())
    .methods(RequestMethod.valueOf(definition.getMethod().toUpperCase()))
    .options(options);

为什么这样能解决问题?

  1. 显式配置: Spring Boot 2.x 中 BuilderConfiguration 默认未配置 PatternParser
  2. 统一路径处理: 通过设置 PathPatternParser 统一路径匹配机制
  3. 正确初始化: 确保 RequestMappingHandlerMapping 能正确处理路径解析

关键差异说明

Spring Boot 2.x vs Spring Boot 3.x:

  • Spring Boot 2.x: BuilderConfiguration 默认未设置 PatternParser,需要手动配置
  • Spring Boot 3.x: BuilderConfiguration 默认已设置 PathPatternParser

总结

在 Spring Boot 2.x 中动态注册 RequestMapping 时:

  • 必须手动配置 RequestMappingInfo.BuilderConfiguration
  • 显式设置 PatternParser 确保路径匹配机制正确
  • 避免因配置不完整导致的路径解析异常

(END)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

catoop

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值