因为Swagger配置引起的Springboot3拦截器不生效,检查SwaggerConfig.java:
@Configuration @ConditionalOnProperty(name = "springdoc.enabled", havingValue = "true", matchIfMissing = true) public class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("XX接口文档") .version("1.0") .description("XX接口文档") .license(new License() .name("Apache 2.0") .url("https://www.apache.org/licenses/LICENSE-2.0.html"))); } /** * 设置静态资源映射 * * @param registry */ protected void addResourceHandlers (ResourceHandlerRegistry registry) { registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
拦截器配置:
MyConfiguration.java
@Configuration public class MyConfiguration implements WebMvcConfigurer { @Autowired private UserInterceptor userInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(userInterceptor).addPathPatterns("/user/**").excludePathPatterns("/public/**"); } }
原因是:
继承了 ,这会导致 Spring Boot 的自动配置失效,包括我们的 中的拦截器配置。
解决方案:
修改
,让它实现 而不是继承正确的SwaggerConfig.java:
@Configuration @ConditionalOnProperty(name = "springdoc.enabled", havingValue = "true", matchIfMissing = true) public class SwaggerConfig implements WebMvcConfigurer { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("XXX接口文档") .version("1.0") .description("XXX接口文档") .license(new License() .name("Apache 2.0") .url("https://www.apache.org/licenses/LICENSE-2.0.html"))); } /** * 设置静态资源映射 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
文章评论