SpringBoot 集成 knife4j (Swagger2)
2024-09-06 10:07:15
SpringBoot 集成 knife4j (Swagger2)
前提 :本文 spring boot版本为 2.6.1 ,knife4j 版本为:3.0.3
1、初始化项目,导入pom依赖
<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-boot-starter -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2、创建Swagger配置类
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.apiInfo())
.select()
// 这里可以指定扫描包的路径 或者 扫描指定的注解
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build().protocols(this.newHashSet("https","http"));
}
@SafeVarargs
private final <T> Set<T> newHashSet(T... ts) {
return ts.length > 0 ? new LinkedHashSet(Arrays.asList(ts)) : null;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger接口文档")
.description("文档描述")
.contact( new Contact("xmStudy","https://www.cnblogs.com/XiaoMingStudy1/","123@qq.com"))
.termsOfServiceUrl("")
.version("1.0")
.build();
}
}
最终项目结构图如下:
3、出现的问题
项目启动失败
4、解决问题
原因分析:在springboot 2.6.0会提示documentationPluginsBootstrapper NullPointerException,具体位置的WebMvcPatternsRequestConditionWrapper中的condition为null。原因是在springboot2.6.0中将SpringMVC 默认路径匹配策略从AntPathMatcher 更改为PathPatternParser,导致出错,解决办法是切换会原先的AntPathMatcher
解决问题:在properties中加上spring.mvc.pathmatch.matching-strategy=ant-path-matcher
5、项目正常启动,访问一下
ip为 ip:port/doc.html, 如 http://localhost:8080/doc.html#/home
6 参考连接
- Knife4j 官方文档:https://doc.xiaominfo.com/knife4j/
- Github地址:https://github.com/xiaoymin/swagger-bootstrap-ui/issues/396
- Gitee地址:https://toscode.gitee.com/xiaoym/knife4j
最新文章
- js 获取当前的时间
- hdu 4898 The Revenge of the Princess’ Knight
- android图片的scaleType属性
- Win7重装后,如何删除cygwin目录?
- data structure | heap
- [转载] 理解RESTful架构
- 《HTML5 从入门到精通--7.6.3 单元格垂直跨度——rowspan》
- Vss服务端用户存在,但客户端登陆不进去
- python学习笔记(五岁以下儿童)深深浅浅的副本复印件,文件和文件夹
- 使用yeoman构建angular应用
- django-rest-framework之序列化
- MongoDB Limit与Skip方法
- 自己动手实现一个Android Studio插件
- JS与IOS、Android的交互
- mysql group by using filesort优化
- IP白名单
- Linux 文件日志筛选操作
- Spring-IOC 扩展点 BeanFactoryPostProcessor及其子接口解析
- python_程序模拟浏览器请求及会话保持
- Jquery Easy UI初步学习(二)datagrid的使用