Manually call Spring Annotation Validation Outside of Spring MVC

霸气de小男生 提交于 2021-02-11 06:58:31

问题


I have the following test that fails:

 @Test
 public void testValidation() {
    Validator validator = new LocalValidatorFactoryBean();
    Map<String, String> map = new HashMap<String, String>();
    MapBindingResult errors = new MapBindingResult(map, Foo.class.getName());

    Foo foo = new Foo();
    foo.setBar("ba");
    validator.validate(foo, errors);
    assertTrue(errors.hasFieldErrors());
 }

Foo is as follows:

import javax.validation.constraints.Size;
public class Foo {
    @Size(min=9, max=9)
    private String bar;

    // ... public setter and getter for bar
}

I have referenced Manually call Spring Annotation Validation and Using Spring Validator outside of the context of Spring MVC but I'm not sure why this test is failing.


回答1:


You are trying to use a bean that is actually to be used inside a Spring ApplicationContext outside of it. To prepare it for use you also have to mimic the behavior of the ApplicationContext in regards to object initialization.

The LocalValidatorFactoryBean implements the InitializingBean interface. Which contains a single method which will be normally called by the ApplicationContext once the object is constructed and all dependencies have been injected (the same as a method annotated with @PostConstruct).

As you are using the bean outside of an ApplicationContext you will have to call the afterPropertiesSet method manually before the object is actually ready to be used.



来源:https://stackoverflow.com/questions/38357936/manually-call-spring-annotation-validation-outside-of-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!