javax.validation如何在验证消息中获取属性名
我正在寻找一种在验证消息中使用属性名的正确方法,如javax.validation如何在验证消息中获取属性名,java,validation,Java,Validation,我正在寻找一种在验证消息中使用属性名的正确方法,如{min}或{regexp} 我已经在谷歌上搜索了好几次这个问题,显然没有一个本地的方法来解决这个问题 @NotNull(message = "The property {propertyName} may not be null.") private String property; 以前是否有人经历过这种情况,并设法找到了解决方案 更新1 使用自定义消息插值器应类似于: public class CustomMessageInterpola
{min}
或{regexp}
我已经在谷歌上搜索了好几次这个问题,显然没有一个本地的方法来解决这个问题
@NotNull(message = "The property {propertyName} may not be null.")
private String property;
以前是否有人经历过这种情况,并设法找到了解决方案
更新1
使用自定义消息插值器应类似于:
public class CustomMessageInterpolator implements MessageInterpolator {
@Override
public String interpolate(String templateString, Context cntxt) {
return templateString.replace("{propertyName}", getPropertyName(cntxt));
}
@Override
public String interpolate(String templateString, Context cntxt, Locale locale) {
return templateString.replace("{propertyName}", getPropertyName(cntxt));
}
private String getPropertyName(Context cntxt) {
//TODO:
return "";
}
}
一种解决方案是使用两条消息并将您的属性名称夹在它们之间:
@NotBlank(message = "{error.notblank.part1of2}Address Line 1{error.notblank.part2of2}")
private String addressLineOne;
然后在消息资源文件中:
error.notblank.part1of2=必须提供以下字段:'
错误.notblank.part2of2='。更正并重新提交。
当验证失败时,它会生成消息“必须提供以下字段:'地址行1'。更正并重新提交。”您始终可以编写一个自定义注释,检查空值并获取一些属性。当然,我考虑过这一点,但不确定这是否是最佳选择。Once不是关于检查空值的新注释。我正在考虑一些创建通用消息的方法,防止为每个属性创建一组验证消息。我读过MessageInterpolator接口,但仍然不知道如何使用它。很好的解决方案。显然,无法截取
MessageInterpolator.Context
上的属性名。无论如何,谢谢大家的回答和评论。如果我能找到这种性质的解决方案,我将与你分享。谢谢