如何在Java SE项目中使用JSR 380 bean验证注释

时间:2018-02-19 15:01:49

标签: java bean-validation

尝试使用JSR 380注释使用main方法运行我的简单程序,但它对我不起作用。

这是代码......

import javax.validation.constraints.Min;

public class MainClass {

    public static void main(String[] args) {

        Request request = new Request(5);
    }
}

class Request{

    public Request(int greaterThan10) {
        super();
        this.greaterThan10 = greaterThan10;
    }

    @Min(value = 10,message= "value should be greater than 10")
    private int greaterThan10;

    public int getOne2Ten() {
        return greaterThan10;
    }

    public void setOne2Ten(int greaterThan10) {
        this.greaterThan10 = greaterThan10;
    }

}

1 个答案:

答案 0 :(得分:1)

如果您的代码未在托管环境(如Java EE或Spring容器)中运行,则必须手动调用Validator API。即你在main()方法中有类似的内容:

Request request = new Request(5);
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Request>> violations = validator.validate(request);