有如下一段代码:
@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);
}
调用的时候报错:
: Name for argument of type [] not specified, and parameter name information not available via reflection.
大概意思是:
Spring 应用程序中的方法参数解析机制无法确定方法参数的名称。这是因为默认情况下,Java 编译时不保留参数名称,而 Spring 需要使用这些名称来将 URL 路径变量或请求参数映射到方法参数。
解决思路也跟简单,一共分为两步:
- 启用 -parameters 编译器标志
确保项目的编译设置中包含 -parameters 标志。此标志指示 Java 编译器在编译的 .class 文件中保留参数名称,使得像 Spring 这样的框架能够在运行时使用这些名称。
在 中添加 maven-compiler-plugin 的配置
<plugin>
<groupId></groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${}</version>
<configuration>
<source>17</source>
<target>17</target>
<encoding>UTF-8</encoding>
<!-- 启用 -parameters 编译器标志 -->
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
- 注解路径变量
即使启用了 -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);
}