spring validation in a desktop application

2019-07-26 22:46发布

问题:

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

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

}

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)

}

回答1:

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

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.

Here is an example.



回答2:

All you need to do is create a BindException object with your object to be validated and full qualified class name.

Then use the ValidationUitls.invokeValidator() method to validate the bean as explained here.

Here is some example code to clarify what I mean:

    ApplicationContext context = new       ClassPathXmlApplicationContext("applicationContext.xml");

    Person person =  context.getBean(Person.class);

    PersonValidator  personValidator = context.getBean(PersonValidator.class);

    BindException errors = new BindException(person, Person.class.getName());
    ValidationUtils.invokeValidator(personValidator, person, errors);

    if(errors.hasErrors()){
        System.out.println(errors.getAllErrors());
    }