Skip to content

Bean validation not picking error translations anymore #18672

Closed

Description

@wiecia

I have a spring boot application with default bean validation through hibernate validator.
I'm using custom messageSource - which in fact just picks up translations from diferrent places.
On my model classes I'm using custom messages like:

@NotBlank(message = "{validation.error.name.blank}")

Using this setup with Spring Boot 2.1.9 everything works fine and my messages are picked up correctly.
With 2.2.0 it shows "{validation.error.name.blank}" as a result. When there is no custom message on annotation: @NotBlank then it shows default message found in ValidationMessages.properties inside validation jar like "must not be blank".

In my WebMvcConfiguration I'm defining validator bean:

@Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource);
        return validator;
    }

I can't find if the is any change according to this in boot or spring framework 5.2

Activity

  1. added
    status: waiting-for-triage
    on Oct 21, 2019
  2. snicoll commented on Oct 21, 2019

    @snicoll
    Member

    This looks like a duplicate of spring-projects/spring-framework#23839. Let's flag this one on hold and let the framework team figures things out before we start investigating here.

  3. added
    status: on-hold
    on Oct 21, 2019
  4. changed the title [-]Spring Boot 2.2.0 bean validation not picking error translations[/-] [+]Bean validation not picking error translations anymore[/+] on Oct 23, 2019
  5. snicoll commented on Oct 23, 2019

    @snicoll
    Member

    The framework regression has been confirmed so please watch the related issue. If something needs to be done here once the issue has been fixed, we can reopen this issue.

  6. added
    for: external-project
    and removed
    status: on-hold
    status: waiting-for-triage
    on Oct 23, 2019
  7. wiecia commented on Oct 23, 2019

    @wiecia
    Author

    Thank you

  8. sbrannen commented on Oct 28, 2019

    @sbrannen
    Member

    I have reproduced the regression in the following standalone test class.

    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.ArgumentMatchers.eq;
    import static org.mockito.Mockito.when;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
    import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    import java.util.Locale;
    
    import javax.validation.ConstraintViolation;
    import javax.validation.Valid;
    import javax.validation.constraints.Max;
    
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    import org.mockito.Mockito;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
    import org.springframework.context.MessageSource;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.stereotype.Controller;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.FieldError;
    import org.springframework.validation.Validator;
    import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @SpringBootTest(
        classes = MessageSourceAndValidationTests.WebConfig.class,
        webEnvironment = WebEnvironment.MOCK)
    class MessageSourceAndValidationTests {
    
    	MockMvc mockMvc;
    
    	@BeforeEach
    	void setup(WebApplicationContext wac) {
    		this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    	}
    
    	@Test
    	void postInvalidForm() throws Exception {
    		this.mockMvc.perform(post("/form").param("number", "11"))//
    				.andDo(print())//
    				.andExpect(status().isOk())//
    				.andExpect(forwardedUrl("number_exceeded_10"));
    	}
    
    	@Configuration
    	// @EnableAutoConfiguration
    	@EnableWebMvc
    	static class WebConfig implements WebMvcConfigurer {
    
    		@Bean
    		MessageSource messageSource() {
    			MessageSource messageSource = Mockito.mock(MessageSource.class);
    			when(messageSource.getMessage(eq("custom.error.max"), any(), any(Locale.class)))//
    					.thenReturn("number_exceeded_{value}");
    			return messageSource;
    		}
    
    		@Override
    		public Validator getValidator() {
    			LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    			validator.setValidationMessageSource(messageSource());
    			return validator;
    		}
    
    		@Bean
    		FormController formController() {
    			return new FormController();
    		}
    
    	}
    
    	static class Form {
    
    		@Max(value = 10, message = "{custom.error.max}")
    		private int number;
    
    		public int getNumber() {
    			return number;
    		}
    
    		public void setNumber(int number) {
    			this.number = number;
    		}
    	}
    
    	@Controller
    	static class FormController {
    
    		@PostMapping("/form")
    		String submit(@Valid Form form, BindingResult errors) {
    			if (!errors.hasFieldErrors("number")) {
    				throw new IllegalStateException("Declarative validation not applied");
    			}
    
    			FieldError fieldError = errors.getFieldError("number");
    			if (fieldError.contains(ConstraintViolation.class)) {
    				return ((ConstraintViolation<?>) fieldError.unwrap(ConstraintViolation.class)).getMessage();
    			}
    
    			return "no_ConstraintViolation_found";
    		}
    
    	}
    
    }

    If you run the test class as-is, it passes.

    If you redeclare WebConfig as follows...

    	@Configuration
    	@EnableAutoConfiguration
    	// @EnableWebMvc
    	static class WebConfig implements WebMvcConfigurer {
            // ...

    ... the test then fails.

    In light of that, I suggest that this issue be reopened and investigated on the Boot side.

    If there are then steps that need to be taken in Framework, please let us know!

  9. added
    type: regression
    and removed
    for: external-project
    on Oct 28, 2019
  10. added this to the milestone on Oct 28, 2019
  11. sbrannen commented on Oct 28, 2019

    @sbrannen
    Member

    See spring-projects/spring-framework@47c8d1d#diff-410b847334e563dc406577806c2d2027 for the changes in Spring MVC that may be the root cause of this regression.

  12. snicoll commented on Oct 29, 2019

    @snicoll
    Member

    It's a timing issue and the fact that the mvcValidator method in EnableWebMvcConfiguration can no longer do its job anymore. To accommodate with various scenarios, we have an override of this method that makes sure to expose either a user-configured mvc validator or the auto-configured one if none is present.

    When we moved to non-proxied configuration class, the bean methods no longer forces the mvcValidator method to be invoked prior to create the RequestMappingHandlerAdapter. As the ValidationAutoConfiguration runs first, there is a bean that matches the requested predicate and can be used.

    Having said all that, I find it odd that the context does not realize there is going to be two beans of that type in the context ultimately. If we ask for a Validator and there is one bean in the context, and one extra bean definition that hasn't been instantiated yet, I'd expect the context to fail with a resolution failure.

  13. snicoll commented on Oct 29, 2019

    @snicoll
    Member

    With the help of @jhoeller, I've something that works locally by adding @Qualifier("mvcValidator") on the injection point. Without that and since we have a @Primary validator, the context doesn't bother to create any other instance.

    We should revisit the existing tests as we have at least one that is supposed to cover that exact use case.

  14. self-assigned this
    on Oct 29, 2019
  15. modified the milestones: , 2.2.1 on Oct 30, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: regression

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions