Swagger3.0 和 Knife4j 的快速上手(SpringBoot)

简介:Knife4j 是为 Java MVC 框架集成 Swagger 生成 Api 文档的增强解决方案,前身是 swagger-bootstrap-ui, 取名 knife4j 是希望它能像一把匕首一样小巧,轻量,并且功能强悍!

1.两种接口文档访问地址

knife4j 访问地址:http://localhost:8080/doc.html
Swagger2.0访问地址:http://localhost:8080/swagger-ui.html
Swagger3.0访问地址:http://localhost:8080/swagger-ui/index.html

2.导入坐标

在模块中的pom.xml文件中引入以下的依赖,如下:

<!-- Swagger 3.0.0 相关依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

<!-- knife4j 3.0.2 相关依赖 -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.2</version>
</dependency>

<!-- Swagger 2.9.2 相关依赖 -->
<!--<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
 -->

3.编写配置文件

//改配置文件和Swagger配置文件一致,只是添加了两个注解
package com.example.swagger.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
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.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
//@EnableSwagger2	   //开启 Swagger2
@EnableOpenApi     //开启 Swagger3 ,可不写
@EnableKnife4j     //开启 knife4j ,可不写
public class Knife4jConfig {
	@Bean
	public Docket createRestApi() {
		// Swagger 2 使用的是:DocumentationType.SWAGGER_2
		// Swagger 3 使用的是:DocumentationType.OAS_30
		return new Docket(DocumentationType.OAS_30)
				// 定义是否开启swagger,false为关闭,可以通过变量控制
				.enable(true)
				// 将api的元信息设置为包含在json ResourceListing响应中。
				.apiInfo(new ApiInfoBuilder()
						.title("Knife4j接口文档")
						// 描述
						.description("平台服务管理api")
						.contact(new Contact("作者", "地址", "邮箱或联系方式))
						.version("1.0.0")
						.build())
				// 分组名称
				.groupName("1.0")
				// 选择哪些接口作为swagger的doc发布
				.select()
				// 要扫描的API(Controller)基础包
				.apis(RequestHandlerSelectors.basePackage("com.example"))
				//                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
				.paths(PathSelectors.any())
				.build();
	}
}

版权声明:本文为a1120467800原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。