środa, 3 sierpnia 2016

Custom and localized messages spring validation API

Put this code inside your web configuration:
    @Bean
    public MessageSource messageSource() {
        return new MessageSourceAutoConfiguration().messageSource();
    }
    
    @Bean(name = "validator")
    public LocalValidatorFactoryBean validator()
    {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource());
        return bean;
    }
     
    @Override
    public Validator getValidator()
    {
        return validator();
    }
and in validation annotation use:
@NotBlank(message = "{not.blank.message}")
private String foo;

In your classloader put file /messages_en.properties:
not.blank.message=Custom not blank message