桌面应用程序中的Spring验证 [英] spring validation in a desktop application

查看:48
本文介绍了桌面应用程序中的Spring验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我有一个我能想象到的最基本的弹簧验证器示例:-).由于它是一个桌面应用程序,因此我没有运行该容器,因此应该在某些时候调用validate.
是否有任何实用程序可以像弹簧容器一样调用validate方法?或调用验证就足够了吗?在这种情况下,我必须通过验证的Errors对象的具体实现是什么?

Here I have a sample of the most basic spring validator I can imagine :-). Since it is a desktop application, i am not running the container, that is supposed to call validate in certain moments.
Is there any utility to invoke the validate method the same way the spring container does? Or calling validate is sufficient? In this case, what is the concrete implementation of Errors object that i have to pass to validate?

以下是示例(主要是装饰性的):

Here is the example (mostly decorative):

首先,我有一个Person类,具有Stirng firstName属性和String secondName属性:

First i have a Person class, with the Stirng firstName property and the String secondName property:

public static class Person {
    public static final String PROP_FIRSTNAME = "firstName";
    String firstName;
    public static final String PROP_SECONDNAME = "secondName";
    String secondName;

    public String getFirstName() {return firstName;}
    public void setFirstName(String firstName) {this.firstName = firstName;}

    public String getSecondName() {return secondName;}
    public void setSecondName(String secondName) {this.secondName = secondName;}

}

然后我有一个PersonValidator,它只是检查Person是否具有非null的firstName:

Then I have a PersonValidator that simply check if the Person has a non-null firstName:

public static class PersonValidator implements Validator {

    public boolean supports(Class<?> clazz) {
        return Person.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, Person.PROP_FIRSTNAME , "First name must be ");
    }

}

好,现在的问题是:如何使用?

Ok, now the problem: how to use it?

public static void main(String [] args) {

    Person p = new Person();

    PersonValidator v = new PersonValidator();

    //HOW TO PERFORM VALIDATION?
    //v.validate(p, null)

}

推荐答案

很明显,我知道这不是您要的,但是就可以了.

Obviously I know this is not what you are asking for, but here it goes.

如果只需要简单验证,并且不打算使用IoC容器,我建议使用

If simple validation is the only thing you are after, and don't plan on using the IoC container I would suggest using BeanValidation or something similar instead.

此处是一个示例.

这篇关于桌面应用程序中的Spring验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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