在Spring MVC之外手动调用Spring注释验证 [英] Manually call Spring Annotation Validation Outside of Spring MVC

查看:87
本文介绍了在Spring MVC之外手动调用Spring注释验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的以下测试失败:

 @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如下:

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

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

我引用了手动调用Spring注释验证

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.

推荐答案

您正在尝试使用实际上在Spring外部的 ApplicationContext 内部使用的bean.要准备使用它,您还必须模仿 ApplicationContext 在对象初始化方面的行为.

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.

LocalValidatorFactoryBean 实现 InitializingBean 接口.包含一个方法,通常在构造对象并注入所有依赖项后,通常由 ApplicationContext 调用该方法(与使用 @PostConstruct 注释的方法相同).

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

当您在 ApplicationContext 之外使用Bean时,必须在实际准备好使用该对象之前手动调用 afterPropertiesSet 方法.

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.

这篇关于在Spring MVC之外手动调用Spring注释验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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