[Swagger2]分组和接口注释及小结
分組和接口注釋及小結(jié)
配置API分組
1、如果沒(méi)有配置分組,默認(rèn)是default。通過(guò)groupName()方法即可配置分組:
2、重啟項(xiàng)目查看分組
3、如何配置多個(gè)分組?配置多個(gè)分組只需要配置多個(gè)docket即可:
@Bean public Docket docket1(){return new Docket(DocumentationType.SWAGGER_2).groupName("group1"); } @Bean public Docket docket2(){return new Docket(DocumentationType.SWAGGER_2).groupName("group2"); } @Bean public Docket docket3(){return new Docket(DocumentationType.SWAGGER_2).groupName("group3"); }4、重啟項(xiàng)目查看即可
實(shí)體配置
package com.xxxx.swagger2.pojo;import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty;// 等價(jià)于@Api() @ApiModel("用戶實(shí)體類") public class User {@ApiModelProperty("用戶名")public String username;@ApiModelProperty("密碼")public String passwrod;} package com.xxxx.swagger2.controller;import com.xxxx.swagger2.pojo.User; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;@Api(tags = "Hello控制類") @RestController public class HelloController {@GetMapping(value = "/hello")public String hello(){return "hello";}// 只要我們的接口中,返回值中存在實(shí)體類,它就會(huì)被掃描到Swagger中@PostMapping(value = "/user")public User user(){return new User();}// Operation 接口 不是放在類上的,是方法@ApiOperation("HelloController中的hello2方法")@GetMapping(value = "/hello2")public String hello2(@ApiParam("用戶名") String username){return "hello"+username;}@ApiOperation("Post測(cè)試類")@GetMapping(value = "/postt")public User postt(@ApiParam("用戶名") User user){return user;}}常用注解
Swagger的所有注解定義在io.swagger.annotations包下
下面列一些經(jīng)常用到的,未列舉出來(lái)的可以另行查閱說(shuō)明:
| @Api(tags = “xxx模塊說(shuō)明”) | 作用在模塊類上 |
| @ApiOperation(“xxx接口說(shuō)明”) | 作用在接口方法上 |
| @ApiModel(“xxxPOJO說(shuō)明”) | 作用在模型類上:如VO、BO |
| @ApiModelProperty(value = “xxx屬性說(shuō)明”,hidden = true) | 作用在類方法和屬性上,hidden設(shè)置為true可以隱藏該屬性 |
| @ApiParam(“xxx參數(shù)說(shuō)明”) | 作用在參數(shù)、方法和字段上,類似@ApiModelProperty |
我們也可以給請(qǐng)求的接口配置一些注釋
@ApiOperation("接口") @PostMapping("/kuang") @ResponseBody public String kuang(@ApiParam("這個(gè)名字會(huì)被返回")String username){return username; }這樣的話,可以給一些比較難理解的屬性或者接口,增加一些配置信息,讓人更容易閱讀!
相較于傳統(tǒng)的Postman或Curl方式測(cè)試接口,使用swagger簡(jiǎn)直就是傻瓜式操作,不需要額外說(shuō)明文檔(寫(xiě)得好本身就是文檔)而且更不容易出錯(cuò),只需要錄入數(shù)據(jù)然后點(diǎn)擊Execute,如果再配合自動(dòng)化框架,可以說(shuō)基本就不需要人為操作了。
Swagger是個(gè)優(yōu)秀的工具,現(xiàn)在國(guó)內(nèi)已經(jīng)有很多的中小型互聯(lián)網(wǎng)公司都在使用它,相較于傳統(tǒng)的要先出Word接口文檔再測(cè)試的方式,顯然這樣也更符合現(xiàn)在的快速迭代開(kāi)發(fā)行情。當(dāng)然了,提醒下大家在正式環(huán)境要記得關(guān)閉Swagger,一來(lái)出于安全考慮二來(lái)也可以節(jié)省運(yùn)行時(shí)內(nèi)存。
總結(jié)
以上是生活随笔為你收集整理的[Swagger2]分组和接口注释及小结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [Swagger2]拓展:其他皮肤
- 下一篇: [mybatis]缓存_缓存有关的设置以