解决 Spring MVC 接收 URL 中的请求参数报错
Name for argument of type [java.lang.String] not specified, and parameter name information not available via reflection. Ensure that the compiler uses the '-parameters' flag.
此问题在 Spring 6.1 之后出现,之前在其他项目中统一解决过,再次遇到,特此记录一下。
示例代码
java
@GetMapping("/test")
public void test(@RequestParam(required = false) String name) {
// 略
}报错信息
关键错误信息如下,错误信息翻译一下:参数类型 [java.lang.String] 的名称未指定,参数名称信息也未通过反射获得。确保编译器使用“-parameters”标志。
text
jakarta.servlet.ServletException: Request processing failed: java.lang.IllegalArgumentException:
Name for argument of type [java.lang.String] not specified, and parameter name information not available via reflection.
Ensure that the compiler uses the '-parameters' flag.修复方法
提示的很清晰,@RequestParam 没有指定参数名称(只要是 URL 接收参数的场景,都会出现此问题,例如:@PathVariable),所以要么增加名称指定,要么编译器增加 -parameters 参数。
在相关注解中增加名称指定
java
@GetMapping("/test")
public void test(@RequestParam(name = "name", required = false) String name) {
// 略
}编译器增加 -parameters 参数
引入后,mvn clean 一下,以防止之前编译结果有影响。
xml
<build>
<plugins>
<!-- 编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>