接口文档生成工具Swagger2的使用
生活随笔
收集整理的這篇文章主要介紹了
接口文档生成工具Swagger2的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、什么是Swagger
Swagger 是一個規范和完整的框架,用于生成、描述、調用和可視化 RESTful 風格的 Web 服務??傮w目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。
作用:
1. 接口的文檔在線自動生成。
2. 功能測試。
二、個人感受
? 我之前一直是項目運行調試,但是發現這樣效率太低,又用了Postman來調試。Postman是谷歌的一個網頁調試工具,非常適合JavaWeb調試。但是現在我要介紹另一個更不錯的,那就是Swagger工具,這里我是用SpringBoot框架來做的。比較簡單的,可以用來學習Swagger來測試前端和后端的運行。就像下面這個圖片,Swagger就是中間Restful接口的一種測試框架,可以單元測試前后端的運行狀態,提高開發效率。
二、在Maven中添加依賴
? 版本Swagger太高出現問題,
i.s.m.p.AbstractSerializableParameter : Illegal DefaultValue null for parameter type integer java.lang.NumberFormatException: For input string: “”at io.swagger.models.parameters.AbstractSerializableParameter.getExample(AbstractSerializableParameter.java:412) ~[swagger-models-1.5.20.jar:1.5.20]原因: if (BaseIntegerProperty.TYPE.equals(type)) {return Long.valueOf(example); }//實體屬性類型是Integer,就把example轉為Long類型,而example默認為"",導致轉換錯誤。所以需要降低版本 swagger-models
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version><exclusions><exclusion><groupId>io.swagger</groupId><artifactId>swagger-models</artifactId></exclusion></exclusions></dependency><dependency><groupId>io.swagger</groupId><artifactId>swagger-models</artifactId><version>1.5.21</version></dependency>三、創建Swagger2的配置類
/*** Swagger2 配置類* 在與spring boot 集成時,放在與application.java 同級的目錄下* 通過@Configuration注解,讓spring來加載該配置* 再通過@EnableSwagger2注解來啟動Swagger2*/ @Configuration @EnableSwagger2 public class Swagger2 {/*** 創建API應用* appinfo()增加API相關信息* 通過select()函數返回一個ApiSelectorBuilder實例,用來控制那些接口暴露給Swagger來展現* 本例采用置頂掃描的包路徑來定義指定要建立API的目錄** @return*/@Beanpublic Docket createRestApi(){Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.xzp.springboot.springboot.controller")).paths(PathSelectors.any()).build();return docket;}/*** 創建改API的基本信息(這些基本信息會展示在文檔頁面中)* 訪問地址: http://項目實際地址/swagger-ui.html* @return*/private ApiInfo apiInfo(){return new ApiInfoBuilder().title("swagger-api文檔").description("swagger文檔 by 13").termsOfServiceUrl("http://www.baidu.com").version("1.0").build();} }四 創建Controller的控制類
public class User implements Serializable {private Integer id;private String name;private String password;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;} } @RestController public class TestSwaggerController {static Map<Integer, User> usersMap = Collections.synchronizedMap(new HashMap<Integer, User>());// 初始化 usersMapstatic {User user = new User();user.setId(1);user.setName("lou1");user.setPassword("111111");User user2 = new User();user2.setId(2);user2.setName("lou2");user2.setPassword("222222");usersMap.put(1, user);usersMap.put(2, user2);}@ApiOperation(value = "獲取用戶列表" , notes = "查看")@GetMapping(value = "/users")public List<User> getUserList(){List<User> users = new ArrayList<>(usersMap.values());return users;}@ApiOperation(value = "新增加用戶" , notes = "根據User對象新增加用戶")@ApiImplicitParam(name = "user" , value = "用戶實體" , required = true , dataType = "User")@PostMapping("/insert")public String postUser(@RequestBody User user){usersMap.put(user.getId(),user);return "新增加成功!";}@ApiOperation(value = "獲取用戶詳細信息" , notes = "根據id來獲取用戶詳細信息")@ApiImplicitParam(name = "id" , value = "用戶id" , required = true , dataType = "int")@GetMapping(value = "/getOne/{id}")public User getUser(@PathVariable Integer id){return usersMap.get(id);}@ApiOperation(value = "更新用戶詳細信息", notes = "")@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用戶id", required = true, dataType = "int"),@ApiImplicitParam(name = "user", value = "用戶實體user", required = true, dataType = "User")})@PutMapping("/users/{id}")public String putUser(@PathVariable Integer id, @RequestBody User user) {User tempUser = usersMap.get(id);tempUser.setName(user.getName());tempUser.setPassword(user.getPassword());usersMap.put(id, tempUser);return "更新成功";}@ApiOperation(value = "刪除用戶", notes = "根據id刪除對象")@ApiImplicitParam(name = "id", value = "用戶id", required = true, dataType = "int")@DeleteMapping("/users/{id}")public String deleteUser(@PathVariable Integer id) {usersMap.remove(id);return "刪除成功";}}成功:
四、Swagger2 的注解使用
- @Api:用在類上,說明該類的作用。
- @ApiOperation:注解來給API增加方法說明。
- @ApiImplicitParams : 用在方法上包含一組參數說明。
- @ApiImplicitParam:用來注解來給方法入參增加說明。
- @ApiResponses:用于表示一組響應
- @ApiResponse:用在@ApiResponses中,一般用于表達一個錯誤的響應信息
- * code:數字,例如400
- * message:信息,例如"請求參數沒填好"
- * response:拋出異常的類
- @ApiModel:描述一個Model的信息(一般用在請求參數無法使用@ApiImplicitParam注解進行描述的時候)
- * @ApiModelProperty:描述一個model的屬性
注意:@ApiImplicitParam的參數說明:
| name:參數名 | |
| dataType:參數類型 | |
| required:參數是否必須傳 | true | false |
| value:說明參數的意思 | |
| defaultValue:參數的默認值 |
關于文件上傳的Swagger2:
@Api("ChatInfoController|圖片和音頻上傳控制器類") @RestController public class ChatInfoController {/*** 上傳圖片接口* @param attach 文件對象* @param request http請求* @return imgSrc:上傳后圖片文件的路徑*/@ApiOperation(value = "上傳圖片",notes = "文件不能超過20M大小,后綴名為png,jpg,gif")@RequestMapping(value = "/uploadImg",method = RequestMethod.POST)@ResponseBodypublic String uploadImg(@RequestParam("file") MultipartFile attach,HttpServletRequest request) {System.out.println("上傳圖片");return FileUp.upFile(attach, request, Constants.IMAGE, true);}/*** 上傳語音接口* @param attach 文件對象* @param request http請求* @return audioSrc:上傳后語音文件的路徑*/@ApiOperation(value = "上傳語音",notes = "文件不能超過20M大小,后綴名為MP3,silk,flv")@RequestMapping(value = "/uploadAudio",method = RequestMethod.POST)@ResponseBodypublic String uploadAudio( @RequestParam("file") MultipartFile attach,HttpServletRequest request) {System.out.println("上傳語音");return FileUp.upFile(attach, request, Constants.AUDIO, true);}}添加注解后啟動springboot,輸入http://localhost:8080/swagger-ui.html即可進入文檔頁面
總結
以上是生活随笔為你收集整理的接口文档生成工具Swagger2的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java基础day21
- 下一篇: Java基础day22