如何在spring Boot 中添加基于条件的@ Nothing约束?

xmq68pz9  于 2023-11-17  发布在  Spring
关注(0)|答案(1)|浏览(157)

我们正在使用spring-boot。我想在java类中添加基于条件的约束。例如。

@Entity
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "user_id")
    private Integer userId;
    @Column(name = "firstName")
    private String firstName;
    @Column(name = "lastName")
    private String lastName;
}

字符串
现在在上面的代码中,我想把@NotNull约束放在lastName属性上,当且仅当firstName属性不为空。

ac1kyiln

ac1kyiln1#

在这种情况下,您可以使用验证组和自定义约束验证器来实现条件验证。下面是一个示例:

@Entity
public class User {
    ...

    @Column(name = "firstName")
    private String firstName;

    @ConditionalNotNull
    @Column(name = "lastName")
    private String lastName;

    ....
}

字符串
现在,定义ConditionalNotvalid注解和相应的ConditionalNotNullValidator:

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ConditionalNotNullValidator.class)
public @interface ConditionalNotNull {
    String message() default "Field must not be null if the condition is met";

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

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

    String value() default "";
}


ConditionalNotNullValidator:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ConditionalNotNullValidator implements ConstraintValidator<ConditionalNotNull, Object> {

    private String field;

    @Override
    public void initialize(ConditionalNotNull constraintAnnotation) {
        this.field = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true; // Null values are accepted, let @NotNull handle it
        }

        try {
            // Use reflection to get the value of the condition field
            Object conditionFieldValue = value.getClass().getDeclaredMethod("get" + capitalize(field)).invoke(value);

            // Check the condition and validate accordingly
            return conditionFieldValue != null;
        } catch (Exception e) {
            throw new IllegalArgumentException("Error accessing condition field", e);
        }
    }

    private String capitalize(String s) {
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }
}


这样,如果firstName字段不为空,则仅使用@ NotName验证lastName字段。如果firstName为空,则lastName被视为有效,而不管其值如何。

相关问题