Spring Boot Mapping Validation Codes to MessageSource Message

旧巷老猫 提交于 2019-12-01 09:30:32

Because of the configuration

@Bean
public LocalValidatorFactoryBean validator(MessageSource messageSource) {
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource);
    return bean;
}

So you're using Bean Validation then spring get the messages from message.properties file that override from org.hibernate.validator.ValidationMessages.properties file using the key javax.validation.constraints.NotNull.message. If you would like to have key-value pairs:

NotNull.user.firstName=This doesn't work
NotNull.firstName=Or this
NotNull.java.lang.String=This doesn't work either
NotNull=And this doesn't work

to work you have to write as follows:

@Autowired
private MessageSource messageSource;

@PostMapping("/users")
public List<ObjectError> testValidation(@Valid @RequestBody User user, BindingResult bindingResult){
   bindingResult.getFieldErrors().forEach(fieldError -> new ObjectError(
   /*Assumes that ObjectError has constructor of ObjectError(String message) */
          messageSource.getMessage(fieldError, Locale.getDefault())
   ));
   return null; 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!