如何验证 Spring-Boot 映射的实体



我正在尝试使用Spring Validator验证以下方案:

@RestController
@RequestMapping("/bankcode-service")
@Validated
public class BankcodeController {
@Autowired
Delegator delegator;
@Autowired
Delegator delegator;
@Autowired
BankcodeRepository bankcodeRepository;
@DeleteMapping(path = "/bankcode", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public DeferredResult<ResponseEntity<String>> lock(@Valid HttpEntity<BankcodeJSONEntity> httpEntity) {
DeferredResult<ResponseEntity<String>> response = new DeferredResult<>();
if (httpEntity.getBody() == null) {
response.setResult(new ResponseEntity<>("The request was empty!", HttpStatus.BAD_REQUEST));
return response;
}
response.setResult(delegator.delegateUseCase(new LockBankcodeProd(bankcodeRepository, httpEntity.getBody())));
return response;
}

使用的 DTO 如下所示:

@Data
public class BankcodeJSONEntity {
@NotNull
@Size(min = 8, max = 8)
private String bankcode;
@NotNull
@Size(min = 11, max = 11)
private String bic;
@NotNull
private String ticket;
@Basic
@Temporal(TemporalType.DATE)
@NotNull
private Date date;
@NotNull
private String category;
@NotNull
private String name;
}

但无论我是否传入:

{"bankcode":"00000000", "bic":"AAAAAAAAAAA", "ticket":"SPOC-000000", "date":"2020-01-17", "category":"Fusion", "name":"Fantasiebank"}

或无效的:

{"bankcode":"21750000", "bic":"AAAAAAAA", "ticket":"SPOC-000000", "date":"2020-01-17", "category":"Fusion", "name":"Fantasiebank"}

没有引发约束验证异常。在许多教程中,我看到验证主要是使用具体的参数而不是 DTO 完成的。DTO验证是否可能,因为在SonarLint降低我的代码质量之前,我只能有7个构造函数参数。

我在这里做错了什么?

请从参数中删除HttpEntity。将参数更改为@Valid BankcodeJSONEntity entity。 因为 HttpEntity 表示 HTTP 请求或响应,包括标头和正文,通常与 RestTemplate 一起使用。对于控制器,通常作为响应包装器。

public DeferredResult<ResponseEntity<String>> lock(@Valid BankcodeJSONEntityentity) {

最新更新