javax.validation如何在验证消息中获取属性名称

len*_*ndc 6 java validation

我正在寻找一种在验证消息中使用属性名称的正确方法,比如{min}{regexp}.

我现在已经搜索了几次这个问题,显然没有本地方法可以做到这一点.

@NotNull(message = "The property {propertyName} may not be null.")
private String property;
Run Code Online (Sandbox Code Playgroud)

有没有人以前经历过这个,并设法找到解决方案?

更新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 "";
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*idS 5

一种解决方案是使用两条消息并将您的属性名称夹在它们之间:

@NotBlank(message = "{error.notblank.part1of2}Address Line 1{error.notblank.part2of2}")
private String addressLineOne;
Run Code Online (Sandbox Code Playgroud)

然后在您的消息资源文件中:

@NotBlank(message = "{error.notblank.part1of2}Address Line 1{error.notblank.part2of2}")
private String addressLineOne;
Run Code Online (Sandbox Code Playgroud)

当验证失败时,它会生成消息“必须提供以下字段:'地址行 1'。更正并重新提交。”