I am using Spring boot 3 Rest Api, with spring-validation-starter.
Even after configuring Message Source and LocalValidatorFactoryBean, as follows
@Bean
@Primary
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource resourceBundleMessageSource= new ReloadableResourceBundleMessageSource();
resourceBundleMessageSource.setBasenames("classpath:messages"); // directory with messages_XX.properties
resourceBundleMessageSource.setUseCodeAsDefaultMessage(false);
//resourceBundleMessageSource.setDefaultLocale(Locale.ENGLISH);
resourceBundleMessageSource.setDefaultEncoding("UTF-8");
resourceBundleMessageSource.setAlwaysUseMessageFormat(true);
return resourceBundleMessageSource;
}
@Bean
@Primary
public LocalValidatorFactoryBean validator(MessageSource messageSource) {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource);
return bean;
}
@Bean
public LocaleResolver localResolver()
{
SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(Locale.US);
return sessionLocaleResolver;
}
and the DTO as
@Getter
@Setter
public class UserInvitationRequest {
@NotEmpty(message = "{email.not.empty}")
String email;
@NotNull
UserType userType;
}
where my message.properties has
email.not.empty=Email cannot be blank
the validation message is not resolved properly, and returning the default validation message provided by jakarta.validation as "must not be null"
I assume the message properties are not getting registered with the validation framework.
Am I doing some thing wrong ?
on validation error, the following should return
ex.getBindingResult().getFieldErrors().getField().getDefaultMessage() // Translated message from messages.properties.
instead of
ex.getBindingResult().getFieldErrors().getField().getDefaultMessage() //"must not be null"