如何将Spring bean注入Validator(休眠) [英] How to inject spring bean into Validator(hibernate)

查看:198
本文介绍了如何将Spring bean注入Validator(休眠)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

spring文档

我已经阅读了以下春季文档:

I have read the following spring documentation:

默认情况下,LocalValidatorFactoryBean配置一个 使用Spring创建的SpringConstraintValidatorFactory ConstraintValidator实例.这允许您自定义 ConstraintValidators像任何其他方法一样可以从依赖注入中受益 其他Spring bean.

By default, the LocalValidatorFactoryBean configures a SpringConstraintValidatorFactory that uses Spring to create ConstraintValidator instances. This allows your custom ConstraintValidators to benefit from dependency injection like any other Spring bean.

我写了自定义验证器:

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>{
    @Autowired
    MyBeanDao dao;
    ...
}

但是在调试中,我看到dao为空.

But in debug I see that dao is null.

请解释我不理解文档或配置错误?

Please, explain I didn't understand documentation or I wrong configured something?

推荐答案

使用Spring Validator,它还实现Bean验证API.

Use Spring Validator, it also implements Bean Validation API.

请参见7.8.2配置Bean验证提供程序:

See 7.8.2 Configuring a Bean Validation Provider:

http://docs.spring. io/spring/docs/current/spring-framework-reference/html/validation.html

您也可以将其用于方法验证,请参阅上面的文档中的"Spring驱动的方法验证"部分.

You can also use it for method validations, see "Spring-driven Method Validation" section in the documentation above.

[UPDATE1]

如果您希望休眠验证持久性,则需要在enityManagerFactory中设置jpa属性 javax.persistence.validation.factory :

If you want hibernate to validate on persist you need to set jpa property javax.persistence.validation.factory in your enityManagerFactory:

            <property name="jpaPropertyMap">
              <map>
                <entry key="javax.persistence.validation.factory" value-ref="validatorFactory" />
              </map>
            </property>

您可能还需要为事件设置验证组,请参阅: http ://docs.jboss.org/hibernate/validator/4.1/reference/zh-CN/html/validator-checkconstraints.html#validator-checkconstraints-orm-hibernateevent

You may also need to set validation groups for events, see: http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-checkconstraints.html#validator-checkconstraints-orm-hibernateevent

这篇关于如何将Spring bean注入Validator(休眠)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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