“SpringBoot"整合"Knife4j” - 快速上手;
环境
- “Knife4j"版本"2.0.9”;
- “Java"版本"1.8.0_202”;
- “Spring Boot"版本"2.5.9”;
- “Windows 11 专业版_22621.2428”;
- “IntelliJ IDEA 2021.1.3(Ultimate Edition)”;
步骤
步骤A
说明
- 创建"Spring Boot"项目;
图片
(1)
(2)
(3)
步骤B
说明
- 添加相关依赖项;
图片
代码
【说明】
- 文件"pom.xml";
- 直接
"CV"
即可;<!-- Knife4j Spring Boot:在线API --> <dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>2.0.9</version> </dependency>
步骤C
说明
- 初次启动项目;
图片
步骤D
说明
- 创建配置类;
图片
代码
【说明】
- 文件"Knife4jConfiguration.java";
package com.example.knife4jdemo.config;import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver; import org.springframework.beans.factory.annotation.Autowired; 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; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;/*** Knife4j配置类** @author SUNxRUN* @version 0.0.1*/ @Configuration @EnableSwagger2WebMvc public class Knife4jConfiguration {/*** 【重要】指定Controller包路径*/private String basePackage = "com.example.knife4jdemo";/*** 分组名称*/private String groupName = "略";/*** 【主页】题目*/private String title = "在线API文档";/*** 【主页】简介*/private String description = "前后交互";/*** 【主页】作者*/private String contactName = "SUNxRUN";/*** 【主页】版本*/private String version = "1.0.0";/*** 【主机】host*/private String host = "http://localhost:8080";/*** 【主页】服务URL*/private String termsOfServiceUrl = "http://www.apache.org/licenses/LICENSE-2.0";/*** 联系网址*/private String contactUrl = "略";/*** 联系邮箱*/private String contactEmail = "略";@Autowiredprivate OpenApiExtensionResolver openApiExtensionResolver;public Knife4jConfiguration() {System.out.println("【配置类】Knife4jConfiguration-----已运行");}@Beanpublic Docket docket() {String groupName = "1.0.0";Docket docket = new Docket(DocumentationType.SWAGGER_2).host(host).apiInfo(apiInfo()).groupName(groupName).select().apis(RequestHandlerSelectors.basePackage(basePackage)).paths(PathSelectors.any()).build().extensions(openApiExtensionResolver.buildExtensions(groupName));return docket;}private ApiInfo apiInfo() {return new ApiInfoBuilder().title(title).description(description).termsOfServiceUrl(termsOfServiceUrl).contact(new Contact(contactName, contactUrl, contactEmail)).version(version).build();}}
步骤E
说明
- 设置配置项;
图片
代码
【说明】
- 文件"application.properties";
# 开启Knife4j增强模式 knife4j.enable=true
步骤F
说明
- 最终启动项目;
图片