自定义Bean验证无效

时间:2016-04-08 16:29:58

标签: java bean-validation

我正在尝试创建自定义bean验证,但由于某种原因它无法正常工作。谁能告诉我这是什么问题?

我的主要课程:

package validationtest;

import java.text.ParseException;

public class Main {

    /**
     * @param args the command line arguments
     * @throws java.text.ParseException
     * @throws java.lang.IllegalAccessException
     */
    public static void main(String[] args) throws ParseException, IllegalArgumentException, IllegalAccessException {
       Text msg = new Text();
       System.out.println(msg.getMessage(""));      
    }

}

class Text {
    public String getMessage(@NotEmpty(message = "Field message") String msg) {
        return msg;
    }
}

我的验证界面

package validationtest;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotEmptyImpl.class)
public @interface NotEmpty {

    String message() default "";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default{};
}

我的验证工具

package validationtest;

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

public class NotEmptyImpl implements ConstraintValidator<NotEmpty, String> {

    @Override
    public void initialize(NotEmpty annotation) {
        throw new RuntimeException("The field is not empty: " + annotation.message());
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }
        return !"".equals(value);
    }

}

注意:我将包验证-api-1.1.0.Final.jar添加到了classpath。

1 个答案:

答案 0 :(得分:1)

您需要添加bean验证的实现,例如 - Hibernate Validator 5.0。 Maven依赖:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.0.Final</version>
</dependency>

然后你需要初始化ValidatorFactory + Validator,并用ExecutableValidator执行方法:

public static void main(String[] args) throws NoSuchMethodException {
    ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    Validator validator = vf.getValidator();

    Text msg = new Text();

    String inParam = "";

    Method method = Text.class.getMethod("getMessage", String.class);
    ExecutableValidator methodValidator = validator. forExecutables();
    Set<ConstraintViolation<Text>> violations =
        methodValidator.validateParameters(msg, method, new Object[]{inParam});
    if (violations.size() > 0) {
        violations.forEach(v -> System.out.println(v.getMessage()));
    } else {
        //if ok - executing method
        msg.getMessage(inParam);
        //or if return value also need validation:
        //violations = methodValidator.validateReturnValue(msg, method, msg.getMessage(""));
        //violations.forEach(v -> System.out.println(v.getMessage()));
    }

    vf.close();
}

输出:

Field message

P.S。并评论&#34;抛出新的...&#34;在NotEmptyImpl