Swagger详解
前言
Github:https://github.com/HealerJean
一、项目构建
1、pom
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2、Swagger3Configuration
package com.healerjean.proj.config;
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.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* Swagger2Configuration
*
* @author zhangyujin
* @date 2023/6/14 19:52.
*/
@Configuration
@EnableOpenApi
public class Swagger3Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.healerjean.proj.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("HealerJean-Swagger-接口列表")
.description("HealerJean-Swagger2 接口文档")
.version("v1.0.0")
.contact(new Contact("HealerJean", "https://blog.healerjean.com", "blog.healerjean.com"))
.license("Apache License, Version 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
}
3、启动
http://localhost:8888/swagger-ui/
二、注解介绍
1、@ApiModel
作用于实体对象
key | 说明 |
---|---|
value |
实体说明 |
description |
实体描述 |
hidden |
默认为 false ,配置为 true 将在文档中隐藏 |
@ApiModel(value = "UserDemoVO视图" ,description = "UserDemoVO视图描述")
@Accessors(chain = true)
@Data
public class UserDemoVO implements Serializable {
2、@ApiModelProperty
作用于实体字段
key | 说明 |
---|---|
value |
字段说明 |
hidden |
默认为 false ,配置为 true 将在文档中隐藏 |
required |
是否必填 |
notes |
字段描述 |
/**
* 名字
*/
@ApiModelProperty(value = "name名字", notes = "name的字段描述")
private String name;
3、@API
作用于接口
key | 说明 |
---|---|
value |
接口说明 |
tag |
描述请求类的作用,非空时会覆盖 value 的值,没必要 |
hidden |
默认为 false ,配置为 true 将在文档中隐藏 |
@RestController
@RequestMapping("hlj")
@Api(value = "UserDemo-控制器", tags = {"增", "删", "改", "查"})
@Slf4j
public class UserDemoController extends BaseController {
4、@ApiOperation
作用于方法
key | 说明 |
---|---|
value |
方法说明 |
tag |
操作标签,非空时将覆盖value 的值,没必要填 |
notes |
方法的备注说明 |
hidden |
默认为 false ,配置为 true 将在文档中隐藏 |
@ApiOperation(value = "用户信息-新增",tags = {"新增用户信息","保存用户信息"}, notes = "用户信息-新增字段描述")
@LogIndex
@PostMapping("user/save")
@ResponseBody
public ResponseBean<Boolean> saveUserDemo(@RequestBody UserDemoSaveReq req) {
UserDemoBO userDemoBo = UserConverter.INSTANCE.covertUserDemoSaveReqToBo(req);
boolean success = userDemoService.saveUserDemo(userDemoBo);
return ResponseBean.buildSuccess(success);
}