Spring Boot Validation国际化消息占位符无法读取注解参数怎么解决?
问题原因
你遇到的占位符解析错误是两个常见配置遗漏导致的:
- 国际化消息占位符使用了错误的索引规则,Spring Validation默认优先支持约束注解属性名作为占位符,索引规则和通用MessageSource的索引规则不一致
- 自定义的校验器没有注册到Spring MVC上下文,Controller参数校验未使用你配置的带自定义MessageSource的校验器
解决方案
第一步:修改国际化消息占位符(推荐)
直接使用注解属性名作为占位符,不需要关心索引顺序,修改消息配置如下:
i18n.reg.validator.firstName.length = Firstname must be between {min} and {max} characters long.
第二步:将自定义校验器注册到Spring MVC
实现WebMvcConfigurer接口,手动指定校验器实现:
@Configuration public class WebValidationConfig implements WebMvcConfigurer { private final LocalValidatorFactoryBean customValidator; public WebValidationConfig(LocalValidatorFactoryBean customValidator) { this.customValidator = customValidator; } @Override public Validator getValidator() { return customValidator; } }
可选:索引占位符适配
如果你需要保留索引写法,需要给校验器配置独立的消息插值器,避免Spring MessageSource提前解析占位符:
@Bean public LocalValidatorFactoryBean validator(MessageSource messageSource) { LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean(); bean.setValidationMessageSource(messageSource); bean.setMessageInterpolator(new ResourceBundleMessageInterpolator( new PlatformResourceBundleLocator("") )); return bean; }
另外需要检查你的DbMessageSource实现,确保返回消息原文时没有提前替换{}占位符,占位符要交给校验器的插值器处理。
内容的提问来源于stack exchange,提问作者user1434702
相关产品推荐
相关产品推荐

