knife4j和swagger文档的简单使用
01 简单使用
1.依赖
<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>
2.加入配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口文档的标题")
.version("1.0.0")
.description("文档的描述")
.build();
}
}
3.配置yml文件
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
4.使用
- 项目启动后在输入localhost:端口号/根路径/swagger-ui.html即可访问程序生成的文档
- 端口号默认8080
- 根路径自己设置,默认没有
02 控制层注解解析
1.@Api
@Api(tags = "类别模块")
@RestController
@RequestMapping("/category")
public class CategoryController {
}
2.@ApiImplicitParam
@ApiImplicitParam(name = "categoryId",value = "类别编号",required = true)
@PostMapping("/post")
public Category post(Long categoryId){
Category category = new Category();
return category;
}
3.@ApiImplicitParam
@ApiImplicitParams({
@ApiImplicitParam(name = "categoryId",value = "类别编号",required = true),
@ApiImplicitParam(name = "categoryName",value = "类别名字",required = true),
@ApiImplicitParam(name = "categoryPicture1",value = "类别图片",required = false),
})
@PostMapping("/set")
public Category set(Long categoryId,String categoryName,String categoryPicture1){
Category category = new Category();
return category;
}
@GetMapping("/delete")
public Category delete(){
Category category = new Category();
return category;
}
- 用于批量设置参数类型
- 可以嵌套@ApiImplicitParam
03 实体类注解解析
@ApiModel("返回实体")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GetData {
@ApiModelProperty("状态码")
private Integer code;
@ApiModelProperty("提示信息")
private String msg;
@ApiModelProperty("返回数据")
private Object data;
public static GetData getData(Integer code, String msg, Object data){
GetData getData = new GetData();
getData.code = code;
getData.msg = msg;
getData.data = data;
return getData;
}
}
1.@ApiModel
2.@ApiModelProperty
04 优化的插件
1.前期准备
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.9</version>
</dependency>
- 修改配置类,在原有基础上修改@EnableSwagger2为@EnableSwagger2WebMvc
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))//扫描的包路径
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口文档的标题")//文档标题
.version("1.0.0")//文档版本说明
.description("文档的描述")//文档的描述
.build();
}
}
2.使用
- 使用方面与之前类似,项目启动后访问localhost:端口号/根路径/doc.html即可