我有从 .raml 文件生成的类。在为 Controller 生成的接口(interface)中,我的参数上有@RequestBody。如果我尝试发出请求,映射工作正常,但每次我的对象中都有空字段,并用参数中的 @RequestBody 注释。看起来这个注释被忽略了。我怎样才能让它从界面工作。
为了在没有 Raml 的情况下进行测试,我尝试为具有简单实现的 Controller 创建一个简单的接口(interface),但我仍然在请求对象中获取空字段值。
从.raml生成的 Controller 接口(interface)
@RestController
@RequestMapping("/kbm")
public interface KbmController {
@RequestMapping(value = "", method = RequestMethod.PUT)
public ResponseEntity<KbmCalcResponse> updateKbm(
@Valid
@RequestBody
KbmCalcRequest kbmCalcRequest);
}
我的实现
@Component
@RequiredArgsConstructor
public class CalcKbmControllerImpl implements KbmController {
private final KbmService kbmService;
@Override
public ResponseEntity<KbmCalcResponse> updateKbm(KbmCalcRequest kbmCalcRequest) {
System.out.println(kbmCalcRequest.getInsurerID());
return ResponseEntity.ok(kbmService.calculate(kbmCalcRequest));
}
}
从 .raml 生成的请求模型
public class KbmCalcRequest implements Serializable
{
final static long serialVersionUID = 1692733266431420440L;
private String insurerID;
public KbmCalcRequest() {
super();
}
public KbmCalcRequest(String insurerID {
super();
this.insurerID = insurerID;
}
public String getInsurerID() {
return insurerID;
}
public void setInsurerID(String insurerID) {
this.insurerID = insurerID;
}
public int hashCode() {
return new HashCodeBuilder().append(insurerID).toHashCode();
}
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other == this) {
return true;
}
if (this.getClass()!= other.getClass()) {
return false;
}
KbmCalcRequest otherObject = ((KbmCalcRequest) other);
return new EqualsBuilder().append(insurerID, otherObject.insurerID).isEquals();
}
public String toString() {
return new ToStringBuilder(this).append("insurerID", insurerID).toString();
}
}
最佳答案
问题出在 Spring Boot 启动器中。我们使用了旧版本的 spring-boot-starter-parent - 2.0.1.RELEASE,它采用了 spring web 4.3.5。但是 Spring Web 的 5.1.0.RELEASE 添加了从方法的参数继承注释到这些方法的实现的功能。因此,我刚刚将最新版本(目前为 2.1.5.RELEASE)放入我的 pom 文件中,它解决了我的问题。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/>
</parent>
关于java - 从接口(interface) Spring @RequestBody,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56377558/