使用 MethodValidationPostProcessor 时 Spring 返回 404

zol*_*olv 0 java validation http-status-code-404 spring-boot

我的测试 Spring Boot 应用程序有问题。它工作得很好,但是当我通过添加依赖项等并添加以下内容来启用 Spring 验证时@Configuration

@Configuration
public class TestConfiguration {

  @Bean
  public MethodValidationPostProcessor methodValidationPostProcessor() {
    return new MethodValidationPostProcessor();
  }
}
Run Code Online (Sandbox Code Playgroud)

我的测试端点得到 404。

{
    "timestamp": 1601507037178,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/test"
}
Run Code Online (Sandbox Code Playgroud)

我已经应用了类似问题的一些解决方案/建议(例如此处此处),但没有成功。

这是我的代码: https: //github.com/zolv/error-handling-test

API接口:

@Validated
public interface TestApi {

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

TestEntity只是为了发送一些东西:

@Data
public class TestEntity {
  @JsonProperty("test")
  @NotNull
  private String test;
}
Run Code Online (Sandbox Code Playgroud)

控制器实现:

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

我的控制器建议:

@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");
  }
}

Run Code Online (Sandbox Code Playgroud)

应用:

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

  public static void main(String[] args) {
    SpringApplication.run(TestApplication.class, args);
  }
}
Run Code Online (Sandbox Code Playgroud)

我使用的测试,但使用 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我注释掉 aTestConfiguration那么一切都会正常。预先感谢您的任何帮助。

And*_*rov 5

您应该进行设置MethodValidationPostProcessor#setProxyTargetClass(true),因为默认情况下MethodValidationPostProcessor使用 JDK 代理,这会导致 Spring 上下文中的控制器丢失。

AbstractHandlerMethodMapping#processCandidateBean调用时isHandler(Class<?> beanType)会返回,false因为JDK代理不包含@RestController注释。

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

Run Code Online (Sandbox Code Playgroud)