【已解决】java.lang.IllegalArgumentException: Name for argument of type [java.lang.Integer] not specified

有如下一段代码:

@GetMapping("/{id}")
@BackendPermission(slug = BPermissionConstant.DEPARTMENT_CUD)
@Log(title = "部门-编辑", businessType = BusinessTypeConstant.GET)
public ApiResponse edit(@PathVariable Integer id) throws NotFoundException {
    Department department = departmentService.findOrFail(id);
    return ApiResponse.data(department);
}

调用的时候报错:

java.lang.IllegalArgumentException: Name for argument of type [java.lang.Integer] not specified, and parameter name information not available via reflection.

大概意思是:
Spring 应用程序中的方法参数解析机制无法确定方法参数的名称。这是因为默认情况下,Java 编译时不保留参数名称,而 Spring 需要使用这些名称来将 URL 路径变量或请求参数映射到方法参数。

解决思路也跟简单,一共分为两步:

  1. 启用 -parameters 编译器标志

确保项目的编译设置中包含 -parameters 标志。此标志指示 Java 编译器在编译的 .class 文件中保留参数名称,使得像 Spring 这样的框架能够在运行时使用这些名称。
在 pom.xml 中添加 maven-compiler-plugin 的配置

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${maven-compiler-plugin.version}</version>
    <configuration>
        <source>17</source>
        <target>17</target>
        <encoding>UTF-8</encoding>
        <!-- 启用 -parameters 编译器标志 -->
        <compilerArgument>-parameters</compilerArgument>
    </configuration>
</plugin>
  1. 注解路径变量

即使启用了 -parameters 标志,最好还是显式地使用 @PathVariable("id") 注解方法参数,以避免任何歧义,特别是如果控制器可能会被不同的工具处理或将来可能会被重构:

@GetMapping("/{id}")
@BackendPermission(slug = BPermissionConstant.DEPARTMENT_CUD)
@Log(title = "部门-编辑", businessType = BusinessTypeConstant.GET)
public ApiResponse edit(@PathVariable(value = "id") Integer id) throws NotFoundException {
    Department department = departmentService.findOrFail(id);
    return ApiResponse.data(department);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

clutch.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值