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

查看:233
本文介绍了Hibernate Validator方法或构造函数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Hibernate验证器验证构造函数或方法中的参数?我希望在ValueObject创建之前进行验证,这样我就可以抛出异常而不创建对象,除非所有参数都有效。

How can I use Hibernate validator to validate the arguments inside the constructor or method? I want the validation to occur before the ValueObject creation so I can throw an exception and not create the object unless all parameters are valid.

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

Basically I'm trying to use annotations instead of doing something like this if possible:

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 似乎有效,但仍会导致创建对象。

I've tried following the docs like this which seems to work but still results in the object being created.

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

在构造函数参数中添加注释似乎没有效果

Adding the annotations to the constructor arguments seems to have no effect

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


推荐答案

找到这篇文章的其他人。
我稍微改变了我的方法,并使用 OVal Validation & AspectJ 而不是Hibernate。

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

基本相同上面的示例,除了我需要在课程上方添加 @Guarded

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

然后在build.gradle中添加:

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

这篇关于Hibernate Validator方法或构造函数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆