Hibernate Validator方法或构造函数验证[英] Hibernate Validator method or constructor validation

问题描述

如何使用Hibernate验证器来验证构造函数或方法内的参数?我希望验证在ValueObject创建之前进行,以便我可以抛出异常,并且除非所有参数都是有效的,否则不会创建对象.

基本上,我正在尝试使用注释,而不是在可能的情况下做这样的事情:

public class ConditionalPerson {
    private String name;
    private String surname;
    private int age;

    public ConditionalPerson(String name, String surname, int age){
        if (name == null || surname == null || age < 1) {
            throw new IllegalArgumentException();
        }
        this.name = name;
        this.surname = surname;
        this.age = age;
    }
}

我已经尝试遵循 docs 像这样看起来似乎有效,但仍会导致对象是创建.

public class Person {
    @NotNull(message = "Name can't be null")
    @NotEmpty(message = "Name can't be empty")
    @Length(min=1)
    private String name;

    @NotNull(message = "Surname can't be null")
    @NotEmpty(message = "Surname can't be empty")
    @Length(min=1)
    private String surname;

    @Range(min=100, max=200)
    private int age;

    public Person(String name, String surname, int age){
        this.name = name;
        this.surname = surname;
        this.age = age;
    }
}

将注释添加到构造函数参数似乎没有效果

public Person(@NotNull String name, 
              @NotNull String surname, 
              @Range(min=100, max=200) int age) { 
    ...
}

我如何创建对象:

public class Example {
    Person person;
    ConditionalPerson person2;

    public static void main(String[] args) {
        Example example = new Example();
        example.makePerson();
        example.makeConditionalPerson();
    }

    public void makePerson() {
        person = new Person(null, "", 12);
        Validator validator = ValidatorSingleton.getValidator();

        Set<ConstraintViolation<Person>> violations = validator.validate(person);

        if (violations.size() > 0) {
            throw new IllegalArgumentException();
        }
    }

    public void makeConditionalPerson() {
        person2 = new ConditionalPerson(null, "", 123);
    }
}

验证器:

public class ValidatorSingleton {
    private static final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    private static final javax.validation.Validator validator = factory.getValidator();

    private ValidatorSingleton(){}

    public static Validator getValidator() {
        return validator;
    }
}

推荐答案

对于任何找到此帖子的人. 我略微改变了方法,并使用椭圆形验证& expackj 而不是冬眠.

基本上与上述示例相同,除了我需要在类上方添加@Guarded:

@Guarded
public class Person {
    private String name;
    private String surname;
    private int age;

    public Person(@NotNull String name, @NotNull String surname, @Range(min=100, max=200) int age){
        this.name = name;
        this.surname = surname;
        this.age = age;
    }
}

然后在您的build.gradle添加:

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'org.aspectj:aspectjtools:1.8.10'
    }
}
dependencies {
    compile 'org.aspectj:aspectjrt:1.8.1'
    compile 'net.sf.oval:oval:1.86'
}

tasks.withType(JavaCompile) {
    doLast {
        String[] args = ["-showWeaveInfo",
                         "-1.8",
                         "-inpath", destinationDir.toString(),
                         "-aspectpath", classpath.asPath,
                         "-d", destinationDir.toString(),
                         "-classpath", classpath.asPath]

        MessageHandler handler = new MessageHandler(true);
        new Main().run(args, handler)
    }

其他推荐答案

您可以使用Hibernate验证器使用Reproction来验证参数:

public class PersonTest {

private static ExecutableValidator executableValidator;

@BeforeClass
public static void setUp() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    executableValidator = factory.getValidator().forExecutables();
}
@Test
public void test() throws NoSuchMethodException {
    Constructor<Person> constructor = 
           Person.class.getConstructor(String.class, String.class, int.class);

    Set<ConstraintViolation<Person>> violations = 
         executableValidator.validateConstructorParameters(constructor, new Object[]{null, "", 12});
         assertEquals(2, violations.size());
    }
}

本文地址:https://www.itbaoku.cn/post/978400.html