Spring引导中的ServletRegistrationBean和ControllerAdvice冲突

时间:2017-11-07 10:23:18

标签: java spring spring-mvc servlets spring-boot

我正在使用Spring boot 1.5.7。 我有一个DispatcherServletCustomConfiguration

的配置类ServletRegistrationBean
ServletRegistrationBean registration = new ServletRegistrationBean(
               dispatcherServlet(), "/api/*");

在项目中存在另一个带有注释@ControllerAdvice的类,带有404和错误处理程序。控制器建议不起作用。 如果我禁用DispatcherServletCustomConfiguration,控制器建议可以正常工作。 你能帮我吗?再见。

更新:

控制器建议:

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers,
            HttpStatus status, WebRequest request) {
        GenericResponse response = new GenericResponse();
        response.getStatus().setCodice(EsitiMapping.NOT_FOUND.getEsito());
        response.getStatus().setDescrizione(EsitiMapping.NOT_FOUND.getDescrizioneEsito());
        response.getStatus().setCodice(EsitiMapping.NOT_FOUND.getCodice());
        //log.error(ex.getMessage(), ex);
        return handleExceptionInternal(ex, response, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
    }

    @ExceptionHandler(value = { Exception.class })
    protected ResponseEntity<Object> handleGenericError(RuntimeException ex, WebRequest request) {
        GenericResponse response = new GenericResponse();
        response.getStatus().setCodice(EsitiMapping.INTERNAL_ERROR.getEsito());
        response.getStatus().setDescrizione(EsitiMapping.INTERNAL_ERROR.getDescrizioneEsito());
        response.getStatus().setCodice(EsitiMapping.INTERNAL_ERROR.getCodice());
        log.error(ex.getMessage(), ex);
        return handleExceptionInternal(ex, response, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }

}

Servlet注册Bean:

@Configuration
public class DispatcherServletCustomConfiguration {

    @Bean
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    @Bean
    public ServletRegistrationBean dispatcherServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(
                dispatcherServlet(), "/api/*");
        registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
        return registration;
    }
}

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:

@Bean
public ServletRegistrationBean dispatcherServletRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(
            dispatcherServlet(), "/api/*");
    dispatcherServlet().setThrowExceptionIfNoHandlerFound(true);
    registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
    return registration;
}

我设置dispatcherServlet().setThrowExceptionIfNoHandlerFound(true);来处理未找到错误的建议。