Spring Boot报错:未指定long类型参数名称,需启用-parameters编译标志
问题解决方法
这个报错的核心原因是Java编译器默认不会把方法参数名存入字节码,导致Spring无法通过反射识别@PathVariable对应的参数名,即使你加了注解也没用。下面是两种解决方式:
方式一:显式指定@PathVariable的参数名
直接在注解里声明路径变量的名称,这样Spring不需要依赖参数元数据就能匹配。修改控制器的方法:
@DeleteMapping("/remove/{code}") public ResponseEntity<ReplyModel> remove(@PathVariable("code") long code) { return as.remove(code); }
方式二:开启编译器的-parameters参数(彻底解决同类问题)
让编译器把参数名写入字节码,这样Spring就能通过反射直接获取参数名,后续无需显式指定注解的name属性。
Maven项目配置
在pom.xml的build节点下添加编译器插件配置:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <!-- 替换为你实际使用的JDK版本 --> <target>1.8</target> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> </plugins> </build>
Gradle项目配置
在build.gradle中添加编译参数:
compileJava { options.compilerArgs << '-parameters' }
额外注意点
你的服务层remove方法里,rm如果是类成员变量会存在线程安全问题,建议每次创建新的ReplyModel实例:
public ResponseEntity<ReplyModel> remove(long code) { ar.deleteById(code); ReplyModel rm = new ReplyModel(); rm.setMensagem("The product has been removed!"); return new ResponseEntity<>(rm, HttpStatus.OK); }
内容的提问来源于stack exchange,提问作者Carlos Maemo
相关产品推荐
相关产品推荐

