Hibernate Validator method or constructor validation

房东的猫 提交于 2019-12-01 12:00:58

For anyone else that finds this post. I changed my approach slightly and got this working using OVal Validation & AspectJ instead of Hibernate.

Basically the same example as above except I needed to add @Guarded above the class:

@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;
    }
}

Then in your build.gradle add:

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)
    }

You can do like this with hibernate validator using refection to validate the arguments:

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());
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!