文档说明、在线调试、离线文档
一、Swagger、knife4j实现
1)引入依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
2)2.6版本需在application.yml文件中添加相关配置
spring: #swagger mvc: pathmatch: matching-strategy: ant_path_matcher
3)添加swagger配置,如文档标题、作者等,在启动类添加两个注解
SwaggerConfig
@Configuration
public class SwaggerConfig {
@Bean
public Docket getDocket(){
ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder();
ApiInfo apiInfo = apiInfoBuilder.title("接口文档")
.description("这是一个接口文档,方便使用者编写代码......")
.version("v 2.0.0")
.contact(new Contact("zhang", "http://localhost:8080","2020474896@qq.com"))
.build();
Docket docket = new Docket(DocumentationType.SWAGGER_2);
docket.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage("com.zs.swagger.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
启动类
@SpringBootApplication
@EnableSwagger2
@EnableKnife4j
@MapperScan("com.zs.swagger.dao")
public class SwaggerApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerApplication.class, args);
}
}
启动项目,访问相关接口文档地址,可在里面进行接口测试。
4)Swagger访问地址
http://localhost:8080/swagger-ui
5)knife4j访问地址
http://localhost:8080/doc.html
二、Swagger相关注解
@Api
参数:tags="说明该类的作用,可在接口文档中看到"
作用:对类的说明,作用在请求类上
@ApiOperation
参数:value="说明方法的用途、作用"
notes="方法的备注说明"
作用:对方法用途、作用的说明,用于请求方法上
@ApiParam
参数:name="参数名"
value="参数说明"
required="是否必填"
作用:对参数添加元数据,参数说明或者参数是否必填,用于方法参数上
@ApiModel
参数:value="对象名"
description="描述"
作用:对实体类进行说明,用于参数用实体类接收,用于类上
@ApiModelProperty
参数:value="字段说明"
name="重写字段名字"
dataType="重写字段类型"
required="是否必填"
example="举例说明"
hidden="隐藏属性"
作用:对Model属性的书名及数据的操作更改,用于方法和字段上
@ApiIgnore
作用:逻辑删除,可以不被Swagger显示在页面上,用于类或者方法上