不使用自动装配的休眠验证器
我目前正在开发 Jersey 项目,并决定使用 Hibernate 验证器进行参数验证。注入 Endpoint 类的所有依赖项均已正确初始化。然而,对于 ConstraintValidator 类中的那些依赖项,它总是抛出 NPE。所以我按照 Spring+hibernate 指南上的指南进行注册
bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
并对需要注入的 ConstraintValidator 类中的服务使用 @Autowired 注解。
使用它有副作用吗?有没有办法避免 ConstraintValidator 类中的自动装配注释并仍然注入值?我尝试在上下文中手动将constraintValidator类注册为bean,添加对我需要的服务的属性引用,但是它引发了空指针异常。
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"
and used the @Autowired annotation for the services in the ConstraintValidator class which needs to be injected.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“Hibernate Validator - JSR 303 Reference Implement - Reference Guide”谈到了有关门户的内容:
那么,这是一件坏事吗?我认为并非如此。当然,您现在已耦合到 DI 容器 (Spring),并且无法轻松重用验证器(例如,当不使用 Spring 时)。另一方面,通过 Spring 工厂构建的验证器,您可以充分利用框架并执行非常繁重的工作(读取实体的修订数据并比较以前的状态,调用任意服务,增强或本地化验证消息,.. .)。
您必须非常小心的一件事是验证器的语义通常是只读的,并且不应通过调用它来引起副作用。例如,不要因为调用(事务)服务或读取验证器内的数据而进行某些自动刷新而意外地将数据刷新到数据库。
"Hibernate Validator - JSR 303 Reference Implementation - Reference Guide" says something about portality:
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.