这个问题的解决方法是:
- 将 DispatcherServlet 配置为在找不到任何处理程序时抛出异常。
- 为将从 DispatcherServlet 引发的异常提供您的实现,本例为
NoHandlerFoundException。
因此,为了配置 DispatcherServlet,您可以使用属性文件或 Java 代码。
properties.yaml 的示例,
spring:
mvc:
throw-exception-if-no-handler-found: true
properties.properties 的示例,
spring.mvn.throw-exception-if-no-handler-found=true
Java代码示例,我们只是想在启动时运行命令servlet.setThrowExceptionIfNoHandlerFound(true);,我使用InitializingBean接口,您可以使用其他方式。我从baeldung 找到了一篇写得很好的指南,可以在春季启动时运行逻辑。
@Component
public class WebConfig implements InitializingBean {
@Autowired
private DispatcherServlet servlet;
@Override
public void afterPropertiesSet() throws Exception {
servlet.setThrowExceptionIfNoHandlerFound(true);
}
}
小心! 在 Spring Boot 2 中添加 @EnableWebMvc 会禁用自动配置,这意味着如果您使用注解 @EnableWebMvc 那么您应该使用 Java 代码示例,因为 spring.mvc.* 属性不会有任何效果。
配置 DispatcherServlet 后,您应该覆盖在抛出异常时调用的 ResponseEntityExceptionHandler。我们希望在抛出 NoHandlerFoundException 时覆盖该操作,如下例所示。
@ControllerAdvice
public class MyApiExceptionHandler extends ResponseEntityExceptionHandler {
@Override
public ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String responseBody = "{\"errormessage\":\"WHATEVER YOU LIKE\"}";
headers.add("Content-Type", "application/json;charset=utf-8");
return handleExceptionInternal(ex, responseBody, headers, HttpStatus.NOT_FOUND, request);
}
}
最后,在ResponseEntityExceptionHandler 的方法handleException 中添加断点可能有助于调试。