You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC请求处理失败:java.lang.IllegalArgumentException错误求助

Spring MVC请求处理失败:参数名称无法通过反射获取的解决办法

问题描述

在Spring MVC应用中遇到请求处理失败问题,具体错误信息如下:

ERROR 7888 --- [nio-8080-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [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.] with root cause

相关代码片段:

@RestController
public class TodoResource {
    private static final List<Todo> TODOS_LIST = List.of(new Todo("lol1","lol1"),
            new Todo("lol2","lol2"));
    @GetMapping("/todos")
    public List<Todo> retriveAllTodos() {
        return TODOS_LIST;
    }

    @GetMapping("/users/{u1}/todos")
    public Todo retriveTodosForSpecificUser(@PathVariable String u1) {
        return TODOS_LIST.get(0);
    }
}
record Todo(String u1, String description) {}

解决方案

方法1:显式指定@PathVariable的参数名称

在@PathVariable注解中明确声明参数名称,与URL路径中的变量名对应,这样Spring无需通过反射获取参数名即可完成映射。修改后的代码如下:

@GetMapping("/users/{u1}/todos")
public Todo retriveTodosForSpecificUser(@PathVariable("u1") String u1) {
    return TODOS_LIST.get(0);
}

方法2:开启编译器-parameters参数

如果不想逐个指定参数名,可以配置编译器在编译时保留参数名称元数据,让Spring能通过反射自动获取参数名。

Maven配置

在项目pom.xml的maven-compiler-plugin中添加编译参数:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <compilerArgs>
                    <arg>-parameters</arg>
                </compilerArgs>
            </configuration>
        </plugin>
    </plugins>
</build>

Gradle配置

在项目build.gradle中添加编译参数:

tasks.withType(JavaCompile) {
    options.compilerArgs << "-parameters"
}

内容的提问来源于stack exchange,提问作者Ankit Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 16:12:09