如何使用 Hibernate Validator 动态解析消息参数?
我正在使用 Hibernate Validator,并希望解析错误消息中的类别名称。考虑这个简单的场景:
public class Category {
private String name;
}
public class Product {
@HazardousCategoryConstraint(message = "{haz.cat.error}")
private Category category;
private String name;
}
public class InventoryReport {
@Valid
private List<Product> products;
}
ValidationMessages.properties
haz.cat.error={name} is a product in the hazardous category list.
假设我有一个 HazardousCategoryConstraint 的有效实现。验证器根据受限名称列表检查每个类别的名称。当我调用 validate(InventoryReport) 时,我得到了预期的错误数量,只不过它们是相同的字符串。我希望看到类别名称解析到每条消息中。有人可以给我提供一个如何动态解析参数的示例,或者告诉我如何做吗?
I'm using Hibernate Validator and would like to resolve the category's name in an error message. Consider this simple scenario:
public class Category {
private String name;
}
public class Product {
@HazardousCategoryConstraint(message = "{haz.cat.error}")
private Category category;
private String name;
}
public class InventoryReport {
@Valid
private List<Product> products;
}
ValidationMessages.properties
haz.cat.error={name} is a product in the hazardous category list.
Assume that I have a working implementation of HazardousCategoryConstraint. The validator checks each Category's name against a list of restricted names. When I call validate(InventoryReport) I get the number of errors I expect except they are the same string. I'd like to see the Category's name resolved into each message. Can someone point me to an example of how to resolve parameters dynamically, or show me how to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IMO,简单的解决方案是创建 javax.validation.MessageInterpolator 的自定义实现。将主要工作委托给 Hibernate Validator 的 ResourceBundleMessageInterpolator 并在 CustomMessageInterpolator 中完成所需的替换工作。
@Test
输出
IMO, the simple solution is to create custom implementation of
javax.validation.MessageInterpolator
. Delegate the main work to Hibernate Validator'sResourceBundleMessageInterpolator
and do the required replacement work inCustomMessageInterpolator
.@Test
Output
在文件中:
.../resources/ValidationMessages.properties
in the file:
.../resources/ValidationMessages.properties