Swagger2+SpringBoot2拦截器不注册的问题

原文地址

注意:SpringBoot2废弃了WebMvcConfigurerAdapter ,请实现WebMvcConfigurationSupport,或者继承WebMvcConfigurer

原因

多个配置类继承WebMvcConfigurationSupport

现象

在SwaggerConfig中,配置SwaggerUI的路径,如下:
1.该类继承自:WebMvcConfigurationSupport 重写addResourceHandlers

@EnableSwagger2
@Configuration
public class SwaggerConfig extends WebMvcConfigurationSupport {
  public static final String DEFAULT_INCLUDE_PATTERN = "/api/.*";

  private static Logger log = LoggerFactory.getLogger(SwaggerConfig.class);
  @Override
  protected void addResourceHandlers(ResourceHandlerRegistry registry) {
     registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
  }

2.InterceptorConfig同样继承自WebMvcConfigurationSupport

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

  private Logger logger = LoggerFactory.getLogger(InterceptorConfig.class);


  @Override
  public void addInterceptors(InterceptorRegistry registry) {
	logger.info("拦截器注册");
	registry.addInterceptor(new ContextInitInterceptor());
	super.addInterceptors(registry);
  }
}

运行时,拦截器注册的日志,没有打印,拦截器没有任何效果。

解决办法

将addResourceHandlers和addInterceptors两个都继承自WebMvcConfigurationSupport合并到一个类中

建议将Swagger中的addResourceHandlers 合并到InterceptorConfig ,按照正常理解来说,这个属于静态资源配置。

改造后:

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

  private Logger logger = LoggerFactory.getLogger(InterceptorConfig.class);


  @Override
  public void addInterceptors(InterceptorRegistry registry) {
	logger.info("拦截器注册");
	registry.addInterceptor(new ContextInitInterceptor()).addPathPatterns("/api/**");
	super.addInterceptors(registry);
  }
  @Override
  protected void addResourceHandlers(ResourceHandlerRegistry registry) {
	registry.addResourceHandler("swagger-ui.html")
			.addResourceLocations("classpath:/META-INF/resources/");

	registry.addResourceHandler("/webjars/**")
			.addResourceLocations("classpath:/META-INF/resources/webjars/");
  }
}

你可能感兴趣的:(SpringBoot2)