【发布时间】:2019-06-26 09:41:59
【问题描述】:
我在 spring-boot 中创建了一个 rest API,问题是我将 4 个参数作为请求体参数作为 JSON 对象。
现在,如果我传递带有 5 个参数的 JSON 对象而不是我的 API 仍然调用,则在序列化 JSON 对象时不会发生断言异常。 我有一个带有构造函数的 dto 类,如下所示
public class testDto{
@NotNull(message = "fistName can not be null.")
private String fistName;
@NotNull(message = "lastName can not be null.")
private String lastName;
private String nickName;
public testDto() {
}
public testDto(@NotNull(message = "fistName can not be null.") final String fistName ,@NotNull(message = "lastName can not be null.") final String lastName , final String nickName){
super();
this.fistName = fistName;
this.lastName = lastName;
this.nickName = nickName;
}
}
我的restapi如下,
@PostMapping(path ={ "/api/v1/user"}, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> saveUser(
@Valid @RequestBody(required = true) final testDto dto) throws Exception {
}
现在在调用我的 API 时,我正在传递请求正文,如下所示
{
"fistName" : "abc",
"lastName" : "xyz",
"nickName" : "pqr",
"age" : 25
}
现在,当我传递 age 参数并调用 API 时,我的 API 仍在工作,而不是为 No any constructor found 引发异常,因为我已经过了年龄,它不是我的 dto 类的成员。
预期结果:不允许调用 API 实际结果:允许我调用API
我也尝试过断言异常声明和绑定异常,但没有取得任何成功。
也设置属性
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
【问题讨论】:
-
你配置
DefaultHandlerExceptionResolver了吗?
标签: java rest spring-boot