本文参考转载:https://oldmoon.top/post/191
简介
使用最新版的springboot 3.2.1(我使用3.2.0)搭建开发环境进行开发,调用接口时出现奇怪的错。报错主要信息如下:
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新版本导致的。为什么会出现这个问题呢?原来是spring 6.1之后,官方加强了很多错误校验和报错提示,本文这个错也是其中之一。
spring表示:url中的传参,必须使用@pathvariable声明用于接收的变量,如:
@deletemapping("/employees/{employeeid}")
public string deleteemployee(@pathvariable int employeeid) {
...
}
@patchmapping("/employees/{id}/{firstname}")
public string patchemployee(@pathvariable integer id, @pathvariable string firstname) {
...
}官方说明中一直强调@pathvariable的使用,并没有提及@requestparam,参考官方文档@requestparam会发现最后有一句话:
note that use of
@requestparamis optional (for example, to set its attributes). by default, any argument that is a simple value type (as determined by beanutils#issimpleproperty) and is not resolved by any other argument resolver, is treated as if it were annotated with@requestparam.翻译一下大概是:
注意
@requestparam的使用是可选的(例如,设置其属性)。 默认情况下,任何简单值类型(由 beanutils#issimpleproperty 确定)且未由任何其他参数解析器解析的参数都将被视为使用@requestparam注解。
根据原文及翻译,这自然让我认为,@requestparam依然是可以省略的。
然而奇怪的是,当springboot 3.2.1使用maven管理项目时,如果不使用spring-boot-starter-parent作为父工程,那么接口中必须显式声明@requestparam("name"),缺了其中的name也会报错。我清晰地记得我在旧版本的 springboot 中经常省略 @requestparam(“name”) 这种写法。
但如果不使用spring-boot-starter-parent作为父工程,好像@requestparam变成了不可省略注解。大家搭建微服务和多模块时候,通常不会使用spring-boot-starter-parent作为父工程吧?还是只有我不用?。。。 还是尽量不要尝试新版本,会少踩很多坑
错误代码
当请求url中有正常参数时,如:http://localhost:8080/user/hello?name=zhangsan,其中name为一个参数,你的controller代码大概如下所示:
@getmapping("/hello")
public resppack<?> hello(string name) {
return null;
}主要pom.xml:
<dependencymanagement>
<dependencies>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-dependencies</artifactid>
<version>${boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencymanagement>
<dependencies>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
</dependencies>解决
这种现象不知道是不是官方的bug,但目前我发现几种解决方案:
- 在参数上使用
@requestparam("name"): - 使用
spring-boot-starter-parent:
<!-- 将spring-boot-starter-parent作为父工程在pom.xml中引入 -->
<parent>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-parent</artifactid>
<version>3.2.1</version>
<relativepath/>
</parent>maven-compiler-plugin
网友提除解决方案:父pom或本身pom中添加maven-compiler-plugin的配置:
<build>
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-compiler-plugin</artifactid>
<version>3.12.0</version>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
</build> 这可确保使用-parameters标志编译代码,从而使参数名称在运行时可用。
到此这篇关于springboot3.x 无法解析parameter参数问题的文章就介绍到这了,更多相关springboot无法解析parameter参数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论