Swagger使用和注釋詳解
一:介紹
1、什么是Swagger
Swagger是一個(gè)規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風(fēng)格的 Web 服務(wù)??傮w目標(biāo)是使客戶端和文件系統(tǒng)作為服務(wù)器以同樣的速度來(lái)更新。文件的方法,參數(shù)和模型緊密集成到服務(wù)器端的代碼,允許API來(lái)始終保持同步。
作用
- 接口文檔在線自動(dòng)生成
- 功能測(cè)試
Swagger是一組開源項(xiàng)目,其中主要要項(xiàng)目如下:
- Swagger-tools:提供各種與Swagger進(jìn)行集成和交互的工具。例如模式檢驗(yàn)、Swagger 1.2文檔轉(zhuǎn)換成Swagger 2.0文檔等功能。
- Swagger-core: 用于Java/Scala的的Swagger實(shí)現(xiàn)。與JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架進(jìn)行集成。
- Swagger-js: 用于JavaScript的Swagger實(shí)現(xiàn)。
- Swagger-node-express: Swagger模塊,用于node.js的Express web應(yīng)用框架。
- Swagger-ui:一個(gè)無(wú)依賴的HTML、JS和CSS集合,可以為Swagger兼容API動(dòng)態(tài)生成優(yōu)雅文檔。
- Swagger-codegen:一個(gè)模板驅(qū)動(dòng)引擎,通過(guò)分析用戶Swagger資源聲明以各種語(yǔ)言生成客戶端代碼。
2、在Spring使用Swagger
在Spring中集成Swagger會(huì)使用到springfox-swagger
,它對(duì)Spring和Swagger的使用進(jìn)行了整合
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox.swagger.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox.swagger.version}</version> </dependency>
二:使用
1、Spring中配置Swagger
/** * Swagger2配置類 * 在與spring boot集成時(shí),放在與Application.java同級(jí)的目錄下。 * 或者通過(guò) @Import 導(dǎo)入配置 */ @Configuration @EnableSwagger2 public class Swagger2 { /** * 創(chuàng)建API應(yīng)用 * apiInfo() 增加API相關(guān)信息 * 通過(guò)select()函數(shù)返回一個(gè)ApiSelectorBuilder實(shí)例,用來(lái)控制哪些接口暴露給Swagger來(lái)展現(xiàn), * 本例采用指定掃描的包路徑來(lái)定義指定要建立API的目錄。 * @return */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.turbo.demo.controller")) .paths(PathSelectors.any()) .build(); } /** * 創(chuàng)建該API的基本信息(這些基本信息會(huì)展現(xiàn)在文檔頁(yè)面中) * 訪問(wèn)地址:http://項(xiàng)目實(shí)際地址/swagger-ui.html * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2構(gòu)建RESTful APIs") .description("") .termsOfServiceUrl("") .contact("zou", "", "zouxq412@foxmail.com") .version("1.0") .build(); } }
2、API注解 @Api
用在類上,該注解將一個(gè)Controller(Class)標(biāo)注為一個(gè)swagger資源(API)。在默認(rèn)情況下,Swagger-Core只會(huì)掃描解析具有@Api注解的類,而會(huì)自動(dòng)忽略其他類別資源(JAX-RS endpoints,Servlets等等)的注解。該注解包含以下幾個(gè)重要屬性
- tags API分組標(biāo)簽。具有相同標(biāo)簽的API將會(huì)被歸并在一組內(nèi)展示。
- value 如果tags沒有定義,value將作為Api的tags使用
- description API的詳細(xì)描述,在1.5.X版本之后不再使用,但實(shí)際發(fā)現(xiàn)在2.0.0版本中仍然可以使用
在指定的(路由)路徑上,對(duì)一個(gè)操作或HTTP方法進(jìn)行描述。具有相同路徑的不同操作會(huì)被歸組為同一個(gè)操作對(duì)象。不同的HTTP請(qǐng)求方法及路徑組合構(gòu)成一個(gè)唯一操作。此注解的屬性有:
- value 對(duì)操作的簡(jiǎn)單說(shuō)明,長(zhǎng)度為120個(gè)字母,60個(gè)漢字。
- notes 對(duì)操作的詳細(xì)說(shuō)明。
- httpMethod HTTP請(qǐng)求的動(dòng)作名,可選值有:"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"。
- code 默認(rèn)為200,有效值必須符合標(biāo)準(zhǔn)的HTTP Status Code Definitions。
@ApiImplicitParams
用在方法上,注解ApiImplicitParam的容器類,以數(shù)組方式存儲(chǔ)。
@ApiImplicitParam
對(duì)API的單一參數(shù)進(jìn)行注解。雖然注解@ApiParam同JAX-RS參數(shù)相綁定,但這個(gè)@ApiImplicitParam注解可以以統(tǒng)一的方式定義參數(shù)列表,也是在Servelet及非JAX-RS環(huán)境下,唯一的方式參數(shù)定義方式。注意這個(gè)注解@ApiImplicitParam必須被包含在注解@ApiImplicitParams之內(nèi)。可以設(shè)置以下重要參數(shù)屬性:
- name 參數(shù)名稱
- value 參數(shù)的簡(jiǎn)短描述
- required 是否為必傳參數(shù)
- dataType 參數(shù)類型,可以為類名,也可以為基本類型(String,int、boolean等)
- paramType 參數(shù)的傳入(請(qǐng)求)類型,可選的值有path, query, body, header or form。
@ApiParam
增加對(duì)參數(shù)的元信息說(shuō)明。這個(gè)注解只能被使用在JAX-RS 1.x/2.x的綜合環(huán)境下。其主要的屬性有
- required 是否為必傳參數(shù),默認(rèn)為false
- value 參數(shù)簡(jiǎn)短說(shuō)明
@ApiResponses
注解@ApiResponse的包裝類,數(shù)組結(jié)構(gòu)。即使需要使用一個(gè)@ApiResponse注解,也需要將@ApiResponse注解包含在注解@ApiResponses內(nèi)。
@ApiResponse
描述一個(gè)操作可能的返回結(jié)果。當(dāng)REST API請(qǐng)求發(fā)生時(shí),這個(gè)注解可用于描述所有可能的成功與錯(cuò)誤碼??梢杂茫部梢圆挥眠@個(gè)注解去描述操作的返回類型,但成功操作的返回類型必須在@ApiOperation中定義。如果API具有不同的返回類型,那么需要分別定義返回值,并將返回類型進(jìn)行關(guān)聯(lián)。但Swagger不支持同一返回碼,多種返回類型的注解。注意:這個(gè)注解必須被包含在@ApiResponses注解中。
- code HTTP請(qǐng)求返回碼。有效值必須符合標(biāo)準(zhǔn)的HTTP Status Code Definitions。
- message 更加易于理解的文本消息
- response 返回類型信息,必須使用完全限定類名,比如“com.xyz.cc.Person.class”。
- responseContainer 如果返回類型為容器類型,可以設(shè)置相應(yīng)的值。有效值為 "List", "Set" or "Map",其他任何無(wú)效的值都會(huì)被忽略。
3、Model注解
對(duì)于Model的注解,Swagger提供了兩個(gè):@ApiModel及@ApiModelProperty,分別用以描述Model及Model內(nèi)的屬性。
@ApiModel
描述一個(gè)Model的信息(一般用在請(qǐng)求參數(shù)無(wú)法使用@ApiImplicitParam注解進(jìn)行描述的時(shí)候)
提供對(duì)Swagger model額外信息的描述。在標(biāo)注@ApiOperation注解的操作內(nèi),所有的類將自動(dòng)被內(nèi)?。╥ntrospected),但利用這個(gè)注解可以做一些更加詳細(xì)的model結(jié)構(gòu)說(shuō)明。主要屬性有:
- value model的別名,默認(rèn)為類名
- description model的詳細(xì)描述
@ApiModelProperty
描述一個(gè)model的屬性
對(duì)model屬性的注解,主要的屬性值有:
- value 屬性簡(jiǎn)短描述
- example 屬性的示例值
- required 是否為必須值
4、注解示例
Api 示例
@AllArgsConstructor @RestController @RequestMapping("/api/category") @Api(value = "/category", tags = "組件分類") public class BizCategoryController { private IBizCategoryService bizCategoryService; @GetMapping("/list") @ApiOperation(value = "列表", notes = "分頁(yè)列表") public R<PageModel<BizCategory>> list(PageQuery pageQuery, @RequestParam @ApiParam("組件分類名稱") String name) { IPage<BizCategory> page = bizCategoryService.page(pageQuery.loadPage(), new LambdaQueryWrapper<BizCategory>().like(BizCategory::getName, name)); return R.success(page); } @GetMapping("/list/all") @ApiOperation(value = "查詢所有", notes = "分頁(yè)列表") public R<List<BizCategory>> listAll() { List<BizCategory> categories = bizCategoryService.list(); return R.success(categories); } @GetMapping("/{categoryId}") @ApiOperation(value = "詳情", notes = "組件分類詳情") public R<BizCategory> detail(@PathVariable @ApiParam("分類Id") Long categoryId) { BizCategory category = bizCategoryService.getById(categoryId); return R.success(category); } @PostMapping("/save") @ApiOperation(value = "保存", notes = "新增或修改") @ApiImplicitParams({ @ApiImplicitParam(paramType = "form", name = "categoryId", value = "組件id(修改時(shí)為必填)"), @ApiImplicitParam(paramType = "form", name = "name", value = "組件分類名稱", required = true) }) public R<BizCategory> save(Long categoryId, String name) { BizCategory category = new BizCategory(); category.setId(categoryId); category.setName(name); bizCategoryService.saveOrUpdate(category); return R.success(category); } @DeleteMapping("/{categoryId}") @ApiOperation(value = "刪除", notes = "刪除") public R delete(@PathVariable @ApiParam("分類Id") Long categoryId) { bizCategoryService.delete(categoryId); return R.success(); } }
ApiModel 示例
@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value="BizComponent對(duì)象", description="組件") public class BizComponent implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; @ApiModelProperty(value = "分類") private Long categoryId; @ApiModelProperty(value = "組件名稱") private String name; @ApiModelProperty(value = "組件描述") private String description; @ApiModelProperty(value = "日期字段") private LocalDateTime componentTime; @ApiModelProperty(value = "創(chuàng)建時(shí)間") @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; @ApiModelProperty(value = "修改時(shí)間") @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime modifiedTime; }
三:swagger-ui界面
swagger生成的api文檔信息接口為/v2/api-docs
,不過(guò)我們可以使用ui界面更加清晰的查看文檔說(shuō)明,并且還能夠在線調(diào)試
1、springfox-swagger-ui
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox.swagger.version}</version> </dependency>
如果是使用springfox-swagger-ui
,啟動(dòng)項(xiàng)目后的api文檔訪問(wèn)路徑是 /swagger-ui.html
2、swagger-bootstrap-ui
swagger-bootstrap-ui是springfox-swagger的增強(qiáng)UI實(shí)現(xiàn),我個(gè)人更推薦使用這個(gè)ui,api文檔結(jié)構(gòu)更加清晰,在線調(diào)試也很方便
<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>${swagger.bootstrap.ui.version}</version> </dependency>
訪問(wèn)的url為 /doc.html
四:Swagger分組
Swagger的分組接口是通過(guò)后端配置不同的掃描包,將后端的接口,按配置的掃描包基礎(chǔ)屬性響應(yīng)給前端
后端java的配置如下,指定分組名和各自要掃描的包
@Bean(value = "defaultApi") public Docket defaultApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .groupName("默認(rèn)接口") .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build(); } @Bean(value = "groupApi") public Docket groupRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(groupApiInfo()) .groupName("分組接口") .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.group")) .paths(PathSelectors.any()) .build(); }
分組信息的接口為 /swagger-resources
[ { "name": "分組接口", "url": "/v2/api-docs?group=分組接口", "swaggerVersion": "2.0", "location": "/v2/api-docs?group=分組接口" },{ "name": "默認(rèn)接口", "url": "/v2/api-docs?group=默認(rèn)接口", "swaggerVersion": "2.0", "location": "/v2/api-docs?group=默認(rèn)接口" } ]
在swagger-ui中也可以通過(guò)分組來(lái)查看api文檔
到此這篇關(guān)于Swagger使用和注釋介紹的文章就介紹到這了,更多相關(guān)Swagger使用和注釋內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談springboot多模塊(modules)開發(fā)
這篇文章主要介紹了淺談springboot多模塊(modules)開發(fā),詳細(xì)的介紹了springboot多模塊的實(shí)現(xiàn),有興趣的可以了解一下2017-09-09springboot 單文件上傳的實(shí)現(xiàn)步驟
這篇文章主要介紹了springboot實(shí)現(xiàn)單文件上傳的方法,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2021-02-02解決weblogic部署springboot項(xiàng)目步驟及可能會(huì)出現(xiàn)的問(wèn)題
這篇文章主要介紹了解決weblogic部署springboot項(xiàng)目步驟及可能會(huì)出現(xiàn)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07Java實(shí)現(xiàn)FIFO、LRU、LFU、OPT頁(yè)面置換算法
本文主要介紹了Java實(shí)現(xiàn)FIFO、LRU、LFU、OPT頁(yè)面置換算法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02java實(shí)現(xiàn)新浪微博Oauth接口發(fā)送圖片和文字的方法
這篇文章主要介紹了java實(shí)現(xiàn)新浪微博Oauth接口發(fā)送圖片和文字的方法,涉及java調(diào)用新浪微博Oauth接口的使用技巧,具有一定參考接借鑒價(jià)值,需要的朋友可以參考下2015-07-07解決static類使用@Value獲取yml文件獲取不到的問(wèn)題
在靜態(tài)類中直接使用@Value注解無(wú)法獲取yml文件中的配置,解決方案是在工具類Utils中創(chuàng)建靜態(tài)的setter方法,并從外部類ServiceClass中調(diào)用這個(gè)方法來(lái)設(shè)置值,這種方法通過(guò)外部調(diào)用來(lái)間接設(shè)置靜態(tài)變量的值,從而成功讀取yml配置2024-09-09