如何在运行时更改注释/Hibernate 验证规则?
如果有一个带有某些字段的 Java 类,我想使用 Hibernate Validator 进行验证。 现在我希望我的用户能够在运行时配置进行哪些验证。
例如:
public class MyPojo {
...
@NotEmpty
String void getMyField() {
...
}
...
}
假设我想删除 NotEmpty
检查或将其替换为 Email
或 CreditCardNumber
,我该怎么做? 有可能吗? 我想这归结为在运行时更改注释......
If have a Java class with some fields I want to validate using Hibernate Validator.
Now I want my users to be able to configure at runtime which validations take place.
For example:
public class MyPojo {
...
@NotEmpty
String void getMyField() {
...
}
...
}
Let's say I want to remove the NotEmpty
check or replace it with Email
or CreditCardNumber
, how can I do it? Is it even possible? I guess it comes down to changing annotations at runtime...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正常情况下你是做不到的。
以下是我通过 Hibernate Validator 获得更多动态验证所做的工作。
ClassValidator
类。getInvalidVaues(Object myObj)
方法。 首先,调用super.getInvalidValues(myObj)
,然后将挂钩添加到您的自定义验证中。getInvalidValues
进行验证。 任何休眠注释验证都将在此时启动,并且您的自定义动态验证(注释不支持的任何内容)也将启动。示例:
因此,您的自定义验证代码可以包含诸如“如果用户配置了此验证,则执行此验证,否则执行此验证”等逻辑。您可能能够也可能无法利用支持休眠验证的相同代码,但是要么方式,您正在做的事情比休眠验证器的“正常”用例更加复杂。
You can't do it normally.
Here's what I've done to get more dynamic validations working via Hibernate Validator.
ClassValidator
class.getInvalidVaues(Object myObj)
method. First, callsuper.getInvalidValues(myObj)
, then add the hook to your customized validation.getInvalidValues
to validate. Any hibernate annotated validations will kick off at this point, and your custom dynamic validations (anything not supported by annotations) will kick off as well.Example:
So your custom validation code can contain logic like "Do this validation, if the user configured it, otherwise do that one", etc. You may or may not be able to leverage the same code that powers the hibernate validations, but either way, what you are doing is more involved that the 'normal' use case for hibernate validator.
实际上在 hibernate validator 4.1 中这是可能的。 只需阅读有关编程约束创建。
Actually it is possible in hibernate validator 4.1. Just read the documentation about programatic constraint creation.
我认为您无法删除或更改注释,它是类定义的一部分。 您可以构建一个新类,这在运行时是可能的,但有点复杂。 Hibernate 可能支持以编程方式访问验证并允许您覆盖注释,我不太了解 API。 Hibernate 本身会进行一些运行时类构建...如果您有兴趣,这可能是学习如何执行此操作的好地方。
I don't think you'll be able to remove or change the annotation, it's part of the class definition. You can build a new class, which is possible at runtime but a little involved. Hibernate may support programmatic access to the validations and allow you to override the annotation, I don't know the API that well. Hibernate does a bit of runtime class building itself... that might be a good place to learn how to do it if you're interested.