【问题标题】:Manually call Spring Annotation Validation Outside of Spring MVC在 Spring MVC 之外手动调用 Spring Annotation Validation
【发布时间】:2016-07-13 17:15:03
【问题描述】:

我有以下测试失败:

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

我引用了Manually call Spring Annotation ValidationUsing Spring Validator outside of the context of Spring MVC,但我不确定为什么这个测试失败了。

【问题讨论】:

  • 在进行验证之前,请在 LocalValidatorFactoryBean 上致电 afterPropertiesSet,否则将无法正确设置。
  • 那是缺失的部分。如果您使用此解决方案发布答案​​,我会将其标记为正确答案。我很好奇您如何确定这是解决方案(例如检查源代码、找到文档等),以便如果您在文档中找到它,我可以阅读更多相关信息。感谢您的帮助。

标签: spring hibernate-validator spring-validator


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 2022-07-17
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多