无需使用自动装配的休眠验证器 [英] hibernate validator without using autowire

查看:99
本文介绍了无需使用自动装配的休眠验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事Jersey项目,并决定使用Hibernate验证程序进行参数验证.注入到Endpoint类的所有依赖项均已正确初始化.但是,对于ConstraintValidator类中的那些依赖项,它总是抛出NPE.因此,我按照Spring + hibernate指南中的指南进行了操作并注册了

I'am currently working on a Jersey project and decided to use Hibernate validator for the parameter validations. All dependencies injected on the Endpoint classes are properly initialized. However for those dependencies in the ConstraintValidator classes, it always throw a NPE. So i followed the guide on Spring+hibernate guide and registered

bean id ="validator" class ="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"

bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"

,并将@Autowired注释用于ConstraintValidator类中需要注入的服务.

and used the @Autowired annotation for the services in the ConstraintValidator class which needs to be injected.

使用它有副作用吗?有没有办法避免ConstraintValidator类中的自动装配注释并仍然注入值?我尝试在上下文中将bean手动注册constraintValidator类,向我需要的服务添加属性引用,但是会引发空指针异常.

are there side effects of using it? Is there a way to avoid the autowiring annotation in ConstraintValidator class and still injecting the values? I tried manually registering the constraintValidator class in the context as bean, adding a property reference to the service that i need, however it throws a null pointer exception.

推荐答案

"Hibernate Validator-JSR 303参考实现-参考指南"中介绍了有关门户的内容:

"Hibernate Validator - JSR 303 Reference Implementation - Reference Guide" says something about portality:

警告

任何依赖ConstraintValidatorFactory的约束实现 特定于实现的行为(依赖项注入,无no-arg 构造函数等)不被视为可移植的.

Any constraint implementation relying on ConstraintValidatorFactory behaviors specific to an implementation (dependency injection, no no-arg constructor and so on) are not considered portable.

那么,这是一件坏事吗?我认为不是.当然,您现在已经耦合到DI容器(Spring),并且无法轻松地重用验证器(例如,当不使用Spring时).另一方面,使用由Spring工厂构建的验证器,您可以充分利用框架并进行繁重的工作(读取实体的修订数据并比较先前的状态,调用任意服务,增强或本地化验证消息,.. ).

So, is it a bad thing? In my opinion it's not. Of course you are now coupled to the DI container (Spring) and can't easily reuse validators (e.g. when not using Spring). On the other hand, with your validators build by a Spring factory you can take full advantage of the framework and do very heavy lifting (read revision data for entities and comparison of previous states, call arbitrary services, enhance or localize validation messages, ...).

您必须非常小心的一件事是,验证器的语义通常是只读的,并且不应通过调用它而引起副作用.例如,不要因调用(事务性)服务或读取验证器中的数据而进行自动刷新而意外地将数据刷新到数据库中.

One thing you must be very careful about is that a validator's semantics is normally read-only and should not cause side-effects by calling it. For example don't accidentally flush data to the database because of some auto-flushing by invoking a (transactional) service or reading data inside your validator.

这篇关于无需使用自动装配的休眠验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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