如何为同一个@Constraint实现多个JSR-303验证消息?

时间:2014-11-07 16:26:05

标签: java hibernate annotations bean-validation hibernate-validator

我正在使用JSR-303验证(hibernate-validator)来实现具有一些不同规则的实体。宁愿不为这些注释堆叠多个@Constraint注释,而是使用单个注释,例如@MyEntityConstraint

问题是每种类型的验证失败确实需要有不同的消息,但消息似乎与注释密不可分:

public @interface MyEntityConstraint {
    String message() default "A single, unchangeable message per constraint???";
    // ...
}

有没有办法围绕这个或我注定要:

@MyEntityConstraint1
@MyEntityConstraint2
// ...
@MyEntityConstraintn
@Entity
public class MyEntity {
    // ...
}

2 个答案:

答案 0 :(得分:7)

根据Hardy的建议,使用ConstraintValidatorContext可以做到这一点 - 如下所示:

@Override
public boolean isValid(MyEntity myEntity, ConstraintValidatorContext context) {
    // Disable default ConstraintViolation so a customised message can be set instead.
    context.disableDefaultConstraintViolation();

    return checkConstraint1(myEntity, context)
           && checkConstraint2(myEntity, context)
           //...
           && checkConstraintn(myEntity, context);
}

// Note: A private method for each constraint decreases the cyclomatic complexity.
private boolean checkConstraint1(MyEntity myEntity, ConstraintValidatorContext context) {
    // Default validity is true until proven otherwise.
    boolean valid = true;

    if (/*<<Insert constraint #1 conditions (about myEntity) here>>*/) {
        valid = false;
        context.buildConstraintViolationWithTemplate(
           "<<Insert constraint #1 failure message here>>").addConstraintViolation();
    }

    return valid;
}

答案 1 :(得分:5)

查看传递给约束验证程序的isValid方法的ConstraintValidatorContext。它允许您自定义错误消息,包括使用不同的消息模板,具体取决于您的验证状态。