SpringBoot 優雅整合Swagger Api 自動生成文檔
- 2021 年 7 月 8 日
- 筆記
- springboot, Swagger
前言
一個好的可持續交付的項目,項目說明,和介面文檔是必不可少的,swagger api
就可以幫我們很容易自動生成api 文檔,不需要單獨額外的去寫,無侵入式,方便快捷大大減少前後端的溝通方便查找和測試介面提高團隊的開發效率方便新人了解項目,剩餘的時間就可以去約妹子啦
整合swagger api
這裡我們自己去整合swagger api比較麻煩,要導入好幾個包,有大神幫我們寫好了輪子kinfe4j直接對應SpringBoot的啟動項,而且在不影響原來使用功能上介面ui做了美化功能做了增強 我們直接整合這個就好了
<!--api 文檔-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.1</version>
</dependency>
正如官網所說
自定義配置資訊
為我們為swagger配置更多的介面說明
package cn.soboys.core.config;
import cn.hutool.core.collection.CollUtil;
import cn.soboys.core.ret.ResultCode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Response;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
/**
* @author kenx
* @version 1.0
* @date 2021/6/21 16:02
* api 配置類
*/
@Configuration
public class SwaggerConfigure {
@Resource
private SwaggerProperty swaggerProperty;
/**
* 構造api 文檔
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30).globalResponses(HttpMethod.POST, this.responseList()) //全局respons資訊
.apiInfo(apiInfo(swaggerProperty)) //文檔資訊
.select()
//文檔掃描
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) //有ApiOperation註解的controller都加入api文檔
.apis(RequestHandlerSelectors.basePackage(swaggerProperty.getBasePackage())) //包模式
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(SwaggerProperty swagger) {
return new ApiInfoBuilder()
//標題
.title(swagger.getTitle())
//描述
.description(swagger.getDescription())
//創建聯繫人資訊 (作者,郵箱,網站)
.contact(new Contact(swagger.getAuthor(), swagger.getUrl(), swagger.getEmail()))
//版本
.version(swagger.getVersion())
//認證
.license(swagger.getLicense())
//認證協議
.licenseUrl(swagger.getLicenseUrl())
.build();
}
/**
* 全局response 返回資訊
* @return
*/
private List<Response> responseList() {
List<Response> responseList = CollUtil.newArrayList();
Arrays.stream(ResultCode.values()).forEach(errorEnum -> {
responseList.add(
new ResponseBuilder().code(errorEnum.getCode().toString()).description(errorEnum.getMessage()).build()
);
});
return responseList;
}
}
抽出api文檔配置模版資訊為屬性文件方便復用
package cn.soboys.core.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
/**
* @author kenx
* @version 1.0
* @date 2021/6/21 16:01
* api 文檔資訊
*/
@Data
@SpringBootConfiguration
public class SwaggerProperty {
/**
* 需要生成api文檔的 類
*/
@Value("${swagger.basePackage}")
private String basePackage;
/**
* api文檔 標題
*/
@Value("${swagger.title}")
private String title;
/**
* api文檔 描述
*/
@Value("${swagger.description}")
private String description;
/**
* api文檔 版本
*/
@Value("${swagger.version}")
private String version;
/**
* api 文檔作者
*/
@Value("${swagger.author}")
private String author;
/**
* api 文檔作者網站
*/
@Value("${swagger.url}")
private String url;
/**
* api文檔作者郵箱
*/
@Value("${swagger.email}")
private String email;
/**
* api 文檔 認證協議
*/
@Value("${swagger.license}")
private String license;
/**
* api 文檔 認證 地址
*/
@Value("${swagger.licenseUrl}")
private String licenseUrl;
}
簡單使用
在你的Controller上添加swagger註解
@Slf4j
@Api(tags = "登錄")
public class LoginController {
private final IUsersService userService;
@PostMapping("/login")
@ApiOperation("用戶登錄")
public String login(@RequestBody UserLoginParams userLoginParams) {
Users u = userService.login(userLoginParams);
return "ok";
}
}
注意如啟用了訪問許可權,還需將swagger相關uri允許匿名訪問
/swagger**/**
/webjars/**
/v3/**
/doc.html
重啟服務,自帶api文檔訪問鏈接為/doc.html
介面如下:
相比較原來介面UI更加漂亮了,資訊更完善功能更強大
Swagger常用註解
Api標記
用在請求的類上,表示對類的說明,也代表了這個類是swagger2的資源
參數:
- tags:說明該類的作用,參數是個數組,可以填多個。
- value=”該參數沒什麼意義,在UI介面上不顯示,所以不用配置”
- description = “用戶基本資訊操作”
ApiOperation標記
用於請求的方法上表示一個http請求的操作
參數:
- value用於方法描述
- notes用於提示內容
- tags可以重新分組(視情況而用)
ApiParam標記
用於請求方法上對請求參數,欄位說明;表示對參數的添加元數據(說明或是否必填等)
參數:
- name–參數名
- value–參數說明
- required–是否必填
ApiModel標記
用於java實體類上表示對類進行說明,用於參數用實體類接收
參數:
- value–表示對象名
- description–描述
都可省略
ApiModelProperty標記
用於方法,欄位; 表示對model屬性的說明或者數據操作更改
參數:
- value–欄位說明
- name–重寫屬性名字
- dataType–重寫屬性類型
- required–是否必填
- example–舉例說明
- hidden–隱藏
@ApiModel(value="user對象",description="用戶對象user")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value="用戶名",name="username",example="xingguo")
private String username;
@ApiModelProperty(value="狀態",name="state",required=true)
private Integer state;
private String password;
private String nickName;
private Integer isDeleted;
@ApiModelProperty(value="id數組",hidden=true)
private String[] ids;
private List<String> idList;
//省略get/set
}
ApiIgnore標記
用於請求類或者方法上,可以不被swagger顯示在頁面上
ApiImplicitParam標記
用於方法表示單獨的請求參數
ApiImplicitParams標記
用於方法,包含多個 @ApiImplicitParam
參數:
- name–參數名
- value–參數說明
- dataType–數據類型
- paramType–參數類型
- example–舉例說明
@ApiOperation("查詢測試")
@GetMapping("select")
//@ApiImplicitParam(name="name",value="用戶名",dataType="String", paramType = "query")
@ApiImplicitParams({
@ApiImplicitParam(name="name",value="用戶名",dataType="string", paramType = "query",example="xingguo"),
@ApiImplicitParam(name="id",value="用戶id",dataType="long", paramType = "query")})
public void select(){
}
總結
- 可以給實體類和介面添加註釋資訊
- 介面文檔實時更新
- 在線測試
- kinfe4j 在swagger API只做增強,不會改變原有任何使用,更多增加使用功能
點擊這裡進入kinfe4j官網文檔
關注公眾號猿人生了解更多內容