
SpringBoot报错日志——knif4j无法访问401
场景重现
依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.6</version>
</dependency>
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.27</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
</dependencies>
application.yaml
:
server:
port: 8081
springdoc:
swagger-ui:
tags-sorter: alpha
group-configs:
- group: bis
display-name: "业务接口文档"
paths-to-match: '/**'
packages-to-scan: com.hmdp.controller
default-flat-param-object: true
knife4j:
# 开启增强配置
enable: true
# 开启生产环境屏蔽(如果是生产环境,需要把下面配置设置true)
# production: true setting:
language: zh-CN
swagger-model-name: 实体类列
结果访问 localhost:8081/doc.html
出现以下错误:
解决方法
1. 添加静态资源处理
在主包下的config
添加 MvcConfig
:
@Configuration
public class MvcConfig extends WebMvcConfigurationSupport {
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
正常到这,问题就解决了,但是,粗心的我,在项目中配置了全局的拦截器,导致如下错误:
2. 设置拦截器
@Configuration
public class MvcConfig extends WebMvcConfigurationSupport {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RefreshInterceptor(stringRedisTemplate)).addPathPatterns("/**").order(0);
registry.addInterceptor(new LoginInterceptor()).excludePathPatterns(
"/doc.html/**",
"/webjars/**",
"/v3/api-docs/**"
).order(1);
}
}
问题解决:
总结
做SpringBoot的项目时,如果有配置拦截器,一定记得要放对应的资源
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 zxb
评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果