目录
一、Knife4j介绍
Knife4j是一个基于Swagger构建的开源Java API文档工具,它为Java开发者提供了生成、展示和调试API文档的功能。它提供了一套美观且功能强大的界面,可以自动生成API文档,并支持接口分组、参数设置、请求示例、响应模型配置等高级功能。
不同版本的SpringBoot项目需要不同版本的依赖,可在官方网址:https://doc.xiaominfo.com/查看
二、在pom.xml中导入依赖
// SpringBoot2.1.8可使用如下版本
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
三、创建Swagger配置依赖,代码如下
//com.ztm.config.Knife4jConfiguration
// 如果后端接口分为用户端和管理端,就在配置类中创建Docket1()和Docket2()
@Configuration
@EnableSwagger2 //根据依赖的版本不同可能是@EnableSwagger2或者@EnableSwagger2WebMvc
public class Knife4jConfiguration {
@Bean
public Docket Docket() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("SpringBoot2-Demo")
.version("2.0")
.description("SpringBoot2-Demo")
.build();
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.groupName("xxx端接口") //分组名称
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage("com.ztm.controller")) //这里指定Controller扫描包路径
.paths(PathSelectors.any())
.build();
return docket;
}
}
四、创建WebMvcConfiguration配置类,设置Knife4j生成的接口文档静态资源映射。
// com.ztm.config.WebMvcConfiguration
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
/**
* 设置Knife4j接口文档静态资源映射
* @param registry
*/
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
五、在controller接口中添加相应的注解描述
- @Api:类上注解,控制整个类生成接口信息的内容。属性tags:类的名称
- @ApiOperation:方法上注解,描述方法的相关消息。属性value:描述方法作用
示例如下:
六、启动项目,访问
http://localhost:8080/doc.html