简体   繁体   English

如何在Java SE 1.6中实现bean验证

[英]How can I achieve bean validation in Java SE 1.6

The project which I work is a simple Java SE program which is ran using public static void main method. 我工作的项目是一个简单的Java SE程序,使用public static void main方法运行。 I have a DTO bean called StudentBean: 我有一个称为StudentBean的DTO bean:

class StudentBean {
    private String firstname;
    private String lastname;
    private Integer id;
    private Integer age;
    //setters and getters
}

I have over 100k student beans stored in a java.util.ArrayList . 我在java.util.ArrayList存储了超过10万个学生bean。 We have set of rules for each field. 我们为每个领域都有一套规则。 For ex, firstname should not be null and empty, age cannot be negative. 例如,名字不能为空和空,年龄不能为负。

How do I write java code for validating hundreds of thousands of beans against the rules we have and write the log for the beans which violates the rules? 如何编写Java代码以根据我们拥有的规则验证成千上万个bean,并为违反规则的bean编写日志?

We thought of writing custom annotations like @NotNull, @NotEmpty, @PositiveNumber and have a validator logic which validates the beans according to the annotations they have on their variables. 我们考虑编写@NotNull, @NotEmpty, @PositiveNumber类的自定义注释@NotNull, @NotEmpty, @PositiveNumber并具有一个验证程序逻辑,该逻辑根据它们在变量上的注释来验证bean。 If you find this good, please point me to online resources which I can use to implement this. 如果您觉得很好,请向我指出可以用来实现此目的的在线资源。

As this is Java SE project, we do not have javax.validation jar, so no scope of using this library. 由于这是Java SE项目,因此我们没有javax.validation jar,因此没有使用此库的范围。 It would be very helpful if we can achieve it using Java SE library only. 如果我们仅使用Java SE库就可以实现它。

You can have a look at hibernate validator, and how to bootstrap the validation. 您可以查看休眠验证器,以及如何引导验证。 There are already constraints you need available out of the box. 开箱即用,已经有您需要的约束。 The fact that this is Java SE project doesn't mean you can't bootstrap validation by yourself. 这是Java SE项目的事实并不意味着您不能自己引导验证。

I would try to keep it simple and just use a method public boolean isValid () within the bean which implement your rules. 我会尝试保持简单,只在实现您的规则的bean中使用public boolean isValid ()方法。 This way you need no annotations and no reflection. 这样,您无需注释也无需反射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM