You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何带参数使用ValidationMessages属性文件?

Spring Boot自定义校验消息参数替换问题

问题场景

我正在使用Spring Boot的校验功能校验字段,已在resources目录下创建ValidationMessages.properties文件,并重写了Size校验的默认提示:

javax.validation.constraints.Size.message=请输入内容,最大长度为{max}。

该配置运行正常,{max}会在运行时被@Size(max = 100)注解中的值自动替换。

现在我定义了一条自定义消息:

my.custom.message=嘿,我的自定义值是{customValue}

需要从以下常量定义出发,在运行时替换{customValue}标记:

private static final String CUSTOM_STRING = "{my.custom.message}";

解决方法

借助Spring MessageSource实现参数替换

Spring Boot自带的MessageSource可以直接读取ValidationMessages.properties中的消息,并完成参数占位符的替换,步骤如下:

  1. 注入MessageSource实例
    在需要处理消息的类中注入MessageSource:
@Autowired
private MessageSource messageSource;
  1. 解析消息并替换参数
    调用getMessage方法,传入消息键、参数数组和当前Locale即可完成替换:
// 替换为你实际的运行时自定义值
String actualCustomValue = "你的自定义内容";
// 解析消息并替换{customValue}
String resolvedMessage = messageSource.getMessage(
    "my.custom.message", 
    new Object[]{actualCustomValue}, 
    LocaleContextHolder.getLocale()
);

执行后resolvedMessage的内容即为嘿,我的自定义值是你的自定义内容。

自定义校验注解中使用的场景

如果是在自定义校验约束的校验器中使用这条消息,可结合ConstraintValidatorContext完成替换:

@Component
public class CustomValidator implements ConstraintValidator<CustomAnnotation, Object> {

    @Autowired
    private MessageSource messageSource;

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        // 编写你的校验逻辑
        boolean isValid = false;
        if (!isValid) {
            String actualCustomValue = "校验时的自定义值";
            // 禁用默认提示,替换为自定义解析后的消息
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(
                messageSource.getMessage(
                    "my.custom.message",
                    new Object[]{actualCustomValue},
                    LocaleContextHolder.getLocale()
                )
            ).addConstraintViolation();
        }
        return isValid;
    }
}

注意事项

  • ValidationMessages.properties会被Spring自动识别,无需额外配置;若需多语言支持,可创建ValidationMessages_zh_CN.properties等对应Locale的文件。
  • 如果不需要国际化,可直接传入Locale.getDefault()作为参数。

内容的提问来源于stack exchange,提问作者Marius Manastireanu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:45:32