1、引入依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
2、在application.xml中进行配置,需要修改packages-to-scan,其他的默认即可
# springdoc-openapi项目配置
springdoc:
swagger-ui:
path: /swagger-ui.html
tags-sorter: alpha
operations-sorter: alpha
api-docs:
path: /v3/api-docs
group-configs:
- group: 'default'
paths-to-match: '/**'
# 需要修改的是这部分,改为自己的controller所在的位置
packages-to-scan: com.xiaominfo.knife4j.demo.web
# knife4j的增强配置,不需要增强可以不配
knife4j:
enable: true
setting:
language: zh_cn
3、knife4j配置类,对接口文档首页进行一些配置,不配置也可运行。
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Knife4jConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("接口文档")
.version("1.0")
.description("接口文档")
);
}
}
4、上述是一个基本的配置步骤了,但是我的系统中会有登录拦截器,所以在一开始没有在拦截器配置放行路径的时候会一直报错401,配置代码如下:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 配置拦截器放行路径
registry.addInterceptor(loginInterceptor).excludePathPatterns("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-ui.html");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 配置拦截器访问静态资源
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}