欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-29 18:36:55
...

原文地址

注意: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/");
  }
}
相关标签: 踩坑