我正在使用Spring MVC和Hibernate验证器4.2.0。在我的类路径/WEB-INF/classes/ValidationMessages.properties中有一个ValidationMessages.properties:
typeMismatch.java.lang.Integer=Must specify an integer value.
typeMismatch.int=Invalid number entered
typeMismatch=Invalid type entered
这可以在Java配置中作为一个bean提供:
@Configuration
@EnableWebMvc
public class WebApplicationConfiguration extends WebMvcConfigurerAdapter {
...
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource resourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
resourceBundleMessageSource.setBasename("ValidationMessages");
return resourceBundleMessageSource;
}
...
它可以很好地从类路径加载ValidationMessages.properties。我的控制器:
@Controller
public class myController {
...
@InitBinder("myForm")
protected void initUserBinder(WebDataBinder binder) {
binder.setValidator(new CustomValidator());
}
...
@ResponseBody
@RequestMapping(value = "/ajax/myRequest", method = RequestMethod.POST)
public CustomResponse ProcessAjaxRequest(
@Valid @ModelAttribute final MyForm myForm,
final BindingResult bindingResult)
throws Exception {
if (bindingResult.hasErrors()) {
return new CustomResponse(bindingResult.getAllErrors());
} else {
..
}
}
...
还有一个自定义验证器:
public class CustomValidator implements Validator {
@Override
public boolean supports(Class c) {
return MyForm.class.equals(c);
}
@Override
public void validate(Object obj, Errors errors) {
..
我的CustomValidator验证工作正常(我手动插入错误消息,不使用消息源),但是在绑定类型不匹配的错误时,我会得到以下异常:
Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'myField'; nested exception is java.lang.NumberFormatException: For input string: "A"
看起来 DataBinder (?) 没有使用我的 messageSource,而是使用了 ValidationMessages.properties 中的代码。我希望从我的属性文件中获取 typeMismatch 代码,而不是异常消息。我也尝试过使用 ResourceBundleMessageSource 替代 ReloadableResourceBundleMessageSource,但没有任何区别。有什么想法吗?