我有一个简单的bean,即:

public class MyBean {

  private boolean selected;

  private String someString;

  ...
}

因此,如果selected为true,我希望someString@NotNull等。

有什么提示,链接如何实现这一行为?

谢谢
强尼

最佳答案

您可以通过使用自定义验证器注释MyBean来实现此目的,例如:

@ValidMyBean
public class MyBean {

  private boolean selected;

  private String someString;

  ...
}

ValidMyBean:
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyBeanValidator.class)
public @interface ValidMyBean {

    boolean allViolationMessages() default true;

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

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

    String message() default "{ValidMyBean.message}";

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

MyBeanValidator:
public final class MyBeanValidator implements
        ConstraintValidator<ValidMyBean, MyBean> {

    @Override
    public void initialize(
            @SuppressWarnings("unused") final ValidMyBean constraintAnnotation) {
    }

    @Override
    public boolean isValid(final MyBean value,
            final ConstraintValidatorContext context) {

        boolean isValid = true;
        //your validation here

        return isValid;
    }
}

09-27 02:34