前言

Knife4j是一个,基于Swagger,集Swagger2OpenAPI3为一体的增强解决方案

  • 基于SpringFox2.x版本提供Swagger2规范的增强扩展
  • 基于Springdoc-openapi项目提供OAS3规范的增强扩展
  • 适配兼容SpringBoot 2.2、2.3、2.4、2.5、2.6、2.7、3.0
  • 兼容OpenAPI 2.0/3.0

官方使用手册API

引入依赖

1
2
3
4
5
6
<!-- knife4j -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>

创建Swagger配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Contact contact = new Contact("作者名", "链接", "邮箱");
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
//.title("swagger-bootstrap-ui-demo RESTful APIs")
.description("# swagger-bootstrap-ui-demo RESTful APIs")
.termsOfServiceUrl("http://www.xx.com/")
.contact(contact)
.version("1.0")
.build())
//分组名称
.groupName("2.X版本")
.select()
//这里指定Controller扫描包路径
// .apis(RequestHandlerSelectors.basePackage("com.github.xiaoymin.knife4j.controller"))
.apis(RequestHandlerSelectors.basePackage("com.demo.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}

访问测试

访问链接:http://localhost:8080/doc.html