Spring Boot集成Hibernate Validator如何自定义Type Mismatch校验错误消息
Spring Boot 自定义参数类型转换不匹配错误消息的正确实现
问题根本原因
你遇到的类型转换错误不属于Hibernate Validator的校验逻辑范畴,是Spring MVC在参数绑定阶段的DataBinder做类型转换时提前抛出的,所以配置javax.validation.constraints前缀的消息规则完全不会生效,这类错误的消息规则由Spring本身的消息解析器处理。
正确配置步骤
1. 调整消息配置文件内容
删除所有带javax.validation.constraints前缀的typeMismatch相关配置,按优先级从高到低添加如下规则(优先级:精确字段匹配>同名字段匹配>同类型匹配>全局默认):
# 精确匹配当前Controller中inputData对象的more字段类型转换错误 typeMismatch.inputData.more=你提供的more字段值非法 # 匹配所有名为more的字段类型转换错误 typeMismatch.more=more字段值格式错误 # 匹配所有Integer类型字段的类型转换错误 typeMismatch.java.lang.Integer={0} 必须是合法整数 # 全局所有类型不匹配错误的默认提示 typeMismatch={0} 格式非法
注意:精确匹配规则中的
inputData对应你Controller方法里@ModelAttribute修饰的参数变量名,如果你给@ModelAttribute指定了name属性,比如@ModelAttribute("data") DummyInputData inputData,则key需要改为typeMismatch.data.more。
2. 可选:显式绑定消息源(默认配置下可跳过)
如果是自定义了MessageSource或者Web相关配置的项目,显式配置将Spring的类型转换、校验逻辑都绑定到你的消息源,添加如下配置类即可:
import org.springframework.context.MessageSource; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebValidationConfig implements WebMvcConfigurer { private final MessageSource messageSource; public WebValidationConfig(MessageSource messageSource) { this.messageSource = messageSource; } @Override public Validator getValidator() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setValidationMessageSource(messageSource); return validator; } @Override public void addFormatters(FormatterRegistry registry) { if (registry instanceof FormattingConversionService) { ((FormattingConversionService) registry).setMessageSource(messageSource); } } }
配置完成后重启项目即可看到自定义的类型转换错误提示生效。
内容的提问来源于stack exchange,提问作者kkochanski
相关产品推荐
相关产品推荐

