Disabling hibernate validation annotations dynamically at runtime?

本秂侑毒 提交于 2019-12-22 00:02:54

问题


Is it possible to turn off certain constraints / annotations per class at runtime? For instance if I wanted to turn of a @NotNull check on a firstName field, is that possible?

This would make testing to see whether a certain constraint is triggered correctly simpler, as I could turn off all the other constraints, and just check that one constraint.


回答1:


Is it possible to turn off certain constraints / annotations per class at runtime? For instance if I wanted to turn of a @NotNull check on a firstName field, is that possible?

No it is not. Bean Validation does not define such a feature. There is an open issue in Hibernate Validator HV-98 which discusses the possibility of reloading metadata, but even there you would need to rebuild the validator factory.

You could override annotations via XML configuration and then recreate the Validator(Factory) instance using different configurations at the time, but that's probably not easy to mange.

This would make testing to see whether a certain constraint is triggered correctly simpler, as I could turn off all the other constraints, and just check that one constraint.

If it is about testing, you can use Validator.validateValue to just validate a given field. Other than that, if you validate the whole object graph and get a set of constraint violations back, you can just iterate over them and inspect the metadata. There is enough information in the metadata to verify that a specific constraints was executed and failed.




回答2:


The hibernate validation annotation are usually used together with database constraints so it does not make sense to change the behavior at runtime. However if you want to do it you can implement your own validators (by overriding existing) and do whatever you want.



来源:https://stackoverflow.com/questions/38087228/disabling-hibernate-validation-annotations-dynamically-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!