在我当前的实现中,SpecialTransactionDTO
的两个字段(transactionMetric
和 transactionRank
)的验证在所有情况下都有效。现在,我作为 @RequestBody 接收的其父类 TransactionDTO 包含一个 boolean 字段 shouldValidate
,指示是否验证 SpecialTransactionDTO
的两个字段。
当 shouldValidate
标志的值为 false 时,我应该如何配置(关闭)验证?
@PostMapping("{id}/transaction/")
@ApiOperation(value = "Create transaction", httpMethod = "POST", response = TransactionDTO.class)
public ResponseEntity<Object> createTransaction(@PathVariable("id") Long accountId,
@Validated({TransactionNumber.class})
@RequestBody TransactionDTO transaction)
throws NotFoundException, URISyntaxException {
TransactionDTO result = transactionService.createTransaction(accountId, transaction);
return ResponseEntity.created(new URI("api/userAccount/" + accountId)).body(result);
}
<小时/>
@JsonSubTypes({
@JsonSubTypes.Type(value = SpecialTransactionDTO.class, name = SpecialTransactionDTO.TYPE),
@JsonSubTypes.Type(value = TransactionDTO.class, name = TransactionDTO.TYPE)
})
public class TransactionDTO {
@NotNull
private Long id;
@NotNull
private String transactionInitiator;
private Boolean shouldValidate;
private String transactionCode;
}
public class SpecialTransactionDTO extends TransactionDTO {
@NotNull
private Long userId;
@Pattern(regexp = "0|\\d{8,11}")
private String transactionMetric;
@Pattern(regexp = "\\d{1,3}")
private String transactionRank;
}
最佳答案
您可以完全消除 @Validated
注释并模仿 Spring 的行为,如下所示:
@PostMapping("{id}/transaction/")
@ApiOperation(value = "Create transaction", httpMethod = "POST", response = TransactionDTO.class)
public ResponseEntity<Object> createTransaction(@PathVariable("id") Long accountId,
@RequestBody TransactionDTO transaction)
throws NotFoundException, URISyntaxException, MethodArgumentNotValidException {
// Check if we should validate here. Spring will convert your MethodArgumentNotValidException into HTTP 400
if(transaction.shouldValidate) {
SpringValidatorAdapter adapter = new SpringValidatorAdapter(validator);
BeanPropertyBindingResult result = new BeanPropertyBindingResult(transaction, transaction.getClass().getName());
adapter.validate(transaction, result, TransactionNumber.class);
if (result.hasErrors()) {
throw new MethodArgumentNotValidException(null, result);
}
}
TransactionDTO result = transactionService.createTransaction(accountId, transaction);
return ResponseEntity.created(new URI("api/userAccount/" + accountId)).body(result);
}
关于Java - 在特殊情况下关闭类字段的 Spring 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209904/