swagger配置專案及簡單使用
現在專案前後端分離了,但是帶來的問題是溝通成本太高,一個引數的大小寫不正確的話,就會修改幾分鐘,這嚴重影響了自己的工作效率,挺不爽,今天讀書的時候知道有swagger這個工具,於是把它集中到專案裡來了。
swagger是一個很好的配置文件的框架,下面是swagger的生態使用圖:
Swagger是一組開源專案,其中主要要專案如下:
1. Swagger-tools:提供各種與Swagger進行整合和互動的工具。例如模式檢驗、Swagger 1.2文件轉換成Swagger 2.0文件等功能。
2. Swagger-core: 用於Java/Scala的的Swagger實現。與JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架進行整合。
3. Swagger-js: 用於JavaScript的Swagger實現。
4. Swagger-node-express: Swagger模組,用於node.js的Express web應用框架。
5. Swagger-ui:一個無依賴的HTML、JS和CSS集合,可以為Swagger相容API動態生成優雅文件。
6. Swagger-codegen:一個模板驅動引擎,通過分析使用者Swagger資源宣告以各種語言生成客戶端程式碼。
2 maven依賴,引入專案中即可
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
3 建立swagger2配置類
package com.swaggerTest; 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.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * Swagger2配置類 * 在與spring boot整合時,放在與Application.java同級的目錄下。 * 通過@Configuration註解,讓Spring來載入該類配置。 * 再通過@EnableSwagger2註解來啟用Swagger2。 */ @Configuration @EnableSwagger2 public class Swagger2 { /** * 建立API應用 * apiInfo() 增加API相關資訊 * 通過select()函式返回一個ApiSelectorBuilder例項,用來控制哪些介面暴露給Swagger來展現, * 本例採用指定掃描的包路徑來定義指定要建立API的目錄。 * * @return */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller")) .paths(PathSelectors.any()) .build(); } /** * 建立該API的基本資訊(這些基本資訊會展現在文件頁面中) * 訪問地址:http://專案實際地址/swagger-ui.html * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2構建RESTful APIs") .description("更多請關注http://www.baidu.com") .termsOfServiceUrl("http://www.baidu.com") .contact("sunf") .version("1.0") .build(); } }
如上程式碼所示,通過createRestApi函式建立Docket的Bean之後,apiInfo()用來建立該Api的基本資訊(這些基本資訊會展現在文件頁面中)。
4 新增文件內容
在完成了上述配置後,其實已經可以生產文件內容,但是這樣的文件主要針對請求本身,描述的主要來源是函式的命名,對使用者並不友好,我們通常需要自己增加一些說明來豐富文件內容。
Swagger使用的註解及其說明:
@Api:用在類上,說明該類的作用。
@ApiOperation:註解來給API增加方法說明。
@ApiImplicitParams : 用在方法上包含一組引數說明。
@ApiImplicitParam:用來註解來給方法入參增加說明。
@ApiResponses:用於表示一組響應
@ApiResponse:用在@ApiResponses中,一般用於表達一個錯誤的響應資訊
l code:數字,例如400
l message:資訊,例如"請求引數沒填好"
l response:丟擲異常的類
@ApiModel:描述一個Model的資訊(一般用在請求引數無法使用@ApiImplicitParam註解進行描述的時候)
l @ApiModelProperty:描述一個model的屬性
注意:@ApiImplicitParam的引數說明:
一個例子:
package com.swaggerTest.controller;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
* 一個用來測試swagger註解的控制器
* 注意@ApiImplicitParam的使用會影響程式執行,如果使用不當可能造成控制器收不到訊息
*
* @author SUNF
*/
@Controller
@RequestMapping("/say")
@Api(value = "SayController|一個用來測試swagger註解的控制器")
public class SayController {
@ResponseBody
@RequestMapping(value ="/getUserName", method= RequestMethod.GET)
@ApiOperation(value="根據使用者編號獲取使用者姓名", notes="test: 僅1和2有正確返回")
@ApiImplicitParam(paramType="query", name = "userNumber", value = "使用者編號", required = true, dataType = "Integer")
public String getUserName(@RequestParam Integer userNumber){
if(userNumber == 1){
return "張三丰";
}
else if(userNumber == 2){
return "慕容復";
}
else{
return "未知";
}
}
@ResponseBody
@RequestMapping("/updatePassword")
@ApiOperation(value="修改使用者密碼", notes="根據使用者id修改密碼")
@ApiImplicitParams({
@ApiImplicitParam(paramType="query", name = "userId", value = "使用者ID", required = true, dataType = "Integer"),
@ApiImplicitParam(paramType="query", name = "password", value = "舊密碼", required = true, dataType = "String"),
@ApiImplicitParam(paramType="query", name = "newPassword", value = "新密碼", required = true, dataType = "String")
})
public String updatePassword(@RequestParam(value="userId") Integer userId, @RequestParam(value="password") String password,
@RequestParam(value="newPassword") String newPassword){
if(userId <= 0 || userId > 2){
return "未知的使用者";
}
if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){
return "密碼不能為空";
}
if(password.equals(newPassword)){
return "新舊密碼不能相同";
}
return "密碼修改成功!";
}
}
一個需要注意的地方:
Conntroller中定義的方法必須在@RequestMapper中顯示的指定RequestMethod型別,否則SawggerUi會預設為全型別皆可訪問, API列表中會生成多條專案。