[英]Annotation based validation on DTO level happens before field level validation like @NotNull @Size etc
我有一個 DTO 類,我將一些字段設為必填字段。 並且,基於另一個類型字段,其中值可以假設為 A & B 如果類型 A,則只需要檢查 1 項可以通過,如果 B 也可以大於 1。
我需要檢查列表在 DTO 類級別中是否至少有 1 個值。 而且,在自定義注釋驗證中,我需要根據 DTO 的類型字段檢查列表的大小。
所以,在 DTO
@NotNull
@Size(min = 1)
private List<@NotBlank String> items;
並且,內部注釋
if (cancelType == CancellationTypeEnum.A && cancelDto.getItems().size() > 1) {
isValid = false;
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
"Only one item can be sent for 'A' cancel type.").addConstraintViolation();
}
但是,由於字段級別稍后發生,如果我為 items 字段傳遞 null,它會轉到此注釋驗證器並拋出 NPE,因為字段為 null 並且我正在嘗試獲取大小
臨時解決方案是我做空檢查,然后檢查大小,但無論如何我們在字段級別給@NotNull。
有沒有辦法在字段級驗證發生后進行類級自定義注釋來驗證。 在這種情況下,它會拋出字段級驗證,因為字段為空並且不會轉到自定義類級注釋
您可以將 JS-303 驗證組(參見此處)與文檔中的@Validated結合使用:
JSR-303 的 Valid 變體,支持驗證組的規范。
例如:
@CheckEnumSize(groups = {Secondary.class})
public class CancelDto {
public CancelDto(List<String> items) {
this.items = items;
}
@NotNull(groups = {Primary.class})
@Size(min = 1)
public List<@NotNull String> items;
public CancellationTypeEnum cancelType;
public List<String> getItems() {
return items;
}
}
其中Primary
是一個簡單的界面:
public interface Primary {
}
和Secondary
相同:
public interface Secondary {
}
最后你可以使用驗證如下:
@Service
@Validated({Primary.class, Secondary.class})
public class CancelService {
public void applyCancel(@Valid CancelDto cancel) {
//TODO
}
}
將上述代碼與CancelDto
與項目為 null 一起使用時,您應該得到:
Caused by: javax.validation.ConstraintViolationException: applyCancel.cancel.items: must not be null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.