Can't get Hibernate Validator working with Spring MessageSource

后端 未结 5 696
北荒
北荒 2021-02-09 17:39

I\'m trying to get Hibernate Validator setup to use messages from a Spring MessageSource. I have the following setup in my messages-context.xml:

<         


        
5条回答
  •  青春惊慌失措
    2021-02-09 18:02

    This had me stumped for a while, but the problem is that you need to register with Spring the Validator used to validate @Controller methods (thanks to this answer for that insight!)

    So if you are using XML config do something along these lines:

    
        
    
    
     
    

    And if you are using javaconfig, do something like this:

    @EnableWebMVC
    @Configuration
    public MyWebAppContext extends WebMvcConfigurerAdapter {
    
    @Bean
    public LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
        validatorFactoryBean.setValidationMessageSource(messageSource);
        return validatorFactoryBean;
    }
    
    @Override
    public Validator getValidator() {
        return validator();
    }
    

    (see Spring Web MVC framework documentation)

提交回复
热议问题