问题
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