Spring Boot 如何在Sping Boot 中进行条件验证?

jrcvhitl  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(54)

我正在开发Spring REST应用程序。
我有一个DTO

private String name;
@
private String nationality;
private String matchType;
private List<NC_Field> ncFields = new ArrayList();
// Getters and Setters

字符串
我有三张table
1.字段表
1.名称清除表

  1. NC_Fields表


的数据

ecfsfe2w

ecfsfe2w1#

你可以用你想要的逻辑定义一个自定义的验证器,然后你可以为这个验证器创建一个自定义的注解,并像@NotNull一样在你的DTO中使用它。

public class CustomValidator implements ConstraintValidator<MyObject, String> {
  .
  .
  .
}

字符串

@Constraint(validatedBy = { CustomValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface ContactInfo {
    String message() default "Invalid value";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}


请参考此链接,例如:https://www.baeldung.com/spring-dynamic-dto-validation

相关问题