【问题标题】:Spring @RequestBody from interface来自接口的 Spring @RequestBody
【发布时间】:2019-10-16 01:39:14
【问题描述】:

我有从 .raml 文件生成的类。在为控制器生成的接口中,我的参数上有@RequestBody。如果我尝试发出请求,则映射工作正确,但每次我的对象中有空字段时,都用参数中的 @RequestBody 注释。看起来这个注释被忽略了。我怎样才能让它从界面工作。

为了在没有 Raml 的情况下进行测试,我尝试为具有简单实现的控制器创建一个简单的接口,但我的请求对象中仍然有空字段值。

从 .raml 生成的控制器接口

@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();
    }

}

【问题讨论】:

  • 您是否尝试过将注解也添加到实现类中?
  • @daniu 是的,在实现中使用注释它工作正常,但我需要从 raml 文件为我生成的 RequestBody 工作表单接口

标签: java spring spring-mvc raml-java-parser


【解决方案1】:

问题出在 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>

【讨论】:

    猜你喜欢
    • 2011-06-11
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2019-06-25
    相关资源
    最近更新 更多