简体   繁体   中英

Spring returns 404 when using MethodValidationPostProcessor

I have a problem with my test Spring Boot app. It works just fine, but when I enable Spring validation by adding dependency etc and adding a @Configuration :

@Configuration
public class TestConfiguration {

  @Bean
  public MethodValidationPostProcessor methodValidationPostProcessor() {
    return new MethodValidationPostProcessor();
  }
}

I get 404 for my test endpoint.

{
    "timestamp": 1601507037178,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/test"
}

I've already applied some solutions/proposals from similar problems (eg here or here ) but without a success.

Here is my code: https://github.com/zolv/error-handling-test

API interface:

@Validated
public interface TestApi {

  @PostMapping(
      value = "/test",
      produces = {"application/json"},
      consumes = {"application/json"})
  @ResponseBody
  ResponseEntity<TestEntity> getTest(@Valid @RequestBody(required = false) TestEntity request);
}

TestEntity just to send something:

@Data
public class TestEntity {
  @JsonProperty("test")
  @NotNull
  private String test;
}

Controller implementation:

@RestController
@RequiredArgsConstructor
@Validated
public class TestController implements TestApi {
  @Override
  @ResponseBody
  public ResponseEntity<TestEntity> getTest(@Valid @RequestBody TestEntity request) {
    return ResponseEntity.ok(request);
  }
}

My controller advice:

@ControllerAdvice
public class DefaultErrorHandlerAdvice extends ResponseEntityExceptionHandler {

  @ExceptionHandler(value = {ConstraintViolationException.class})
  @ResponseStatus(value = HttpStatus.BAD_REQUEST)
  @ResponseBody
  public ResponseEntity<String> handleValidationFailure(ConstraintViolationException ex) {
    StringBuilder messages = new StringBuilder();

    for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
      messages.append(violation.getMessage());
    }

    return ResponseEntity.badRequest().body(messages.toString());
  }

  @Override
  @ResponseBody
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  protected ResponseEntity<Object> handleMethodArgumentNotValid(
      MethodArgumentNotValidException ex,
      HttpHeaders headers,
      HttpStatus status,
      WebRequest request) {
    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
        .contentType(MediaType.APPLICATION_PROBLEM_JSON)
        .body("problem");
  }
}

Application:

@SpringBootApplication
@EnableWebMvc
@ComponentScan(basePackages = "com.test")
public class TestApplication {

  public static void main(String[] args) {
    SpringApplication.run(TestApplication.class, args);
  }
}

A test I use, but it fails also using Postman:

@SpringJUnitConfig
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class TestControllerTest {

  @Autowired protected TestRestTemplate restTemplate;

  @Test
  void registrationHappyPath() throws Exception {
    /*
     * Given
     */
    final TestEntity request = new TestEntity();

    /*
     * When/
     */
    final ResponseEntity<String> response =
        restTemplate.postForEntity("/test", request, String.class);

    /*
     * Then
     */
    Assertions.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());

    final String body = response.getBody();
    Assertions.assertNotNull(body);
  }
}

If I comment out a TestConfiguration then everything works fine. Thank You in advance for any help.

You should set MethodValidationPostProcessor#setProxyTargetClass(true) because by default MethodValidationPostProcessor uses JDK proxy which leads to loss of your controller in the Spring context.

When AbstractHandlerMethodMapping#processCandidateBean is called isHandler(Class<?> beanType) will return false because JDK proxy doesn't contain @RestController annotation.

  public MethodValidationPostProcessor methodValidationPostProcessor() {
    MethodValidationPostProcessor mvProcessor = new MethodValidationPostProcessor();
    mvProcessor.setProxyTargetClass(true);
    return mvProcessor;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM