1:認識Swagger
Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。整體目標是使客戶端和文件系統做爲服務器以一樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,容許API來始終保持同步。html
做用:java
1. 接口的文檔在線自動生成。node
2. 功能測試。git
Swagger是一組開源項目,其中主要要項目以下:github
1. Swagger-tools:提供各類與Swagger進行集成和交互的工具。例如模式檢驗、Swagger 1.2文檔轉換成Swagger 2.0文檔等功能。web
2. Swagger-core: 用於Java/Scala的的Swagger實現。與JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架進行集成。spring
3. Swagger-js: 用於JavaScript的Swagger實現。express
4. Swagger-node-express: Swagger模塊,用於node.js的Express web應用框架。api
5. Swagger-ui:一個無依賴的HTML、JS和CSS集合,能夠爲Swagger兼容API動態生成優雅文檔。springboot
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配置類
在Application.java同級建立Swagger2的配置類Swagger2
-
-
-
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;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public Docket createRestApi() {
-
return new Docket(DocumentationType.SWAGGER_2)
-
-
-
.apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller"))
-
.paths(PathSelectors.any())
-
-
-
-
-
-
-
-
-
private ApiInfo apiInfo() {
-
return new ApiInfoBuilder()
-
.title("Spring Boot中使用Swagger2構建RESTful APIs")
-
.description("更多請關注http://www.baidu.com")
-
.termsOfServiceUrl("http://www.baidu.com")
-
-
-
-
-
如上代碼所示,經過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的參數說明:
paramType:指定參數放在哪一個地方 |
header:請求參數放置於Request Header,使用@RequestHeader獲取 query:請求參數放置於請求地址,使用@RequestParam獲取 path:(用於restful接口)-->請求參數的獲取:@PathVariable body:(不經常使用) form(不經常使用) |
name:參數名 |
|
dataType:參數類型 |
|
required:參數是否必須傳 |
true | false |
value:說明參數的意思 |
|
defaultValue:參數的默認值 |
|
例子:
-
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;
-
-
-
-
-
-
-
-
-
-
@Api(value = "SayController|一個用來測試swagger註解的控制器")
-
public class SayController {
-
-
-
@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){
-
-
-
-
else if(userNumber == 2){
-
-
-
-
-
-
-
-
-
@RequestMapping("/updatePassword")
-
@ApiOperation(value="修改用戶密碼", notes="根據用戶id修改密碼")
-
-
@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){
-
-
-
if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){
-
-
-
if(password.equals(newPassword)){
-
-
-
-
-
完成上述代碼添加上,啓動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html
![](http://static.javashuo.com/static/loading.gif)
如上圖,能夠看到暴漏出來的控制器信息,點擊進入能夠看到詳細信息。
![](http://static.javashuo.com/static/loading.gif)
兩個注意點:
1. paramType會直接影響程序的運行期,若是paramType與方法參數獲取使用的註解不一致,會直接影響到參數的接收。
例如:
![](http://static.javashuo.com/static/loading.gif)
使用Sawgger UI進行測試,接收不到!
![](http://static.javashuo.com/static/loading.gif)
2. 還有一個須要注意的地方:
Conntroller中定義的方法必須在@RequestMapper中顯示的指定RequestMethod類型,不然SawggerUi會默認爲全類型皆可訪問, API列表中會生成多條項目。
![](http://static.javashuo.com/static/loading.gif)
如上圖:updatePassword()未指定requestMethod,結果生成了7條API信息。因此若是沒有特殊需求,建議根據實際狀況加上requestMethod。
![](http://static.javashuo.com/static/loading.gif)
5:Swagger UI面板說明
![](http://static.javashuo.com/static/loading.gif)
6:參考
http://blog.didispace.com/springbootswagger2/
http://blog.csdn.net/jia20003/article/details/50700736
Swagger官網 :http://swagger.io/
Spring Boot & Swagger UI : http://fruzenshtein.com/spring-boot-swagger-ui/
Github:https://github.com/swagger-api/swagger-core/wiki/Annotations
---------------------------------------------------------------------------------------
7:接收對象傳參的例子
在POJO上增長
-
package com.zhongying.api.model.base;
-
-
import io.swagger.annotations.ApiModel;
-
import io.swagger.annotations.ApiModelProperty;
-
-
-
-
-
-
-
@ApiModel(value="醫生對象模型")
-
-
@ApiModelProperty(value="id" ,required=true)
-
-
@ApiModelProperty(value="醫生姓名" ,required=true)
-
-
-
-
-
-
-
-
public void setId(Integer id) {
-
-
-
-
public String getName() {
-
-
-
-
public void setName(String name) {
-
-
-
-
-
public String toString() {
-
return "DemoDoctor [id=" + id + ", name=" + name + "]";
-
-
-
-
注意: 在後臺採用對象接收參數時,Swagger自帶的工具採用的是JSON傳參, 測試時須要在參數上加入@RequestBody,正常運行採用form或URL提交時候請刪除。
-
package com.zhongying.api.controller.app;
-
-
import java.util.ArrayList;
-
-
-
import javax.servlet.http.HttpServletRequest;
-
-
import org.springframework.stereotype.Controller;
-
import org.springframework.web.bind.annotation.RequestBody;
-
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 com.github.pagehelper.PageInfo;
-
import com.zhongying.api.exception.HttpStatus401Exception;
-
import com.zhongying.api.model.base.DemoDoctor;
-
-
import io.swagger.annotations.Api;
-
import io.swagger.annotations.ApiImplicitParam;
-
import io.swagger.annotations.ApiImplicitParams;
-
import io.swagger.annotations.ApiOperation;
-
-
-
-
-
-
@RequestMapping("/api/v1")
-
-
@Api(value = "DoctorTestController-醫生信息接口模擬")
-
public class DoctorTestController {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@RequestMapping(value="/doctor", method= RequestMethod.POST )
-
@ApiOperation(value="添加醫生信息", notes="")
-
public String addDoctor(@RequestBody DemoDoctor doctor) throws Exception{
-
if(null == doctor || doctor.getId() == null){
-
throw new HttpStatus401Exception("添加醫生失敗","DT3388","未知緣由","請聯繫管理員");
-
-
-
System.
out.println("成功----------->"+doctor.getName());
-
-
throw new HttpStatus401Exception("添加醫生失敗","DT3388","未知緣由","請聯繫管理員");
-
-
-
return doctor.getId().toString();
-
-
-
-
-
-
-
-
-
@RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.DELETE )
-
@ApiOperation(value="刪除醫生信息", notes="")
-
@ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer")
-
public String deleteDoctor(@RequestParam Integer doctorId){
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.POST )
-
@ApiOperation(value="修改醫生信息", notes="")
-
@ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer")
-
public String updateDoctor(@RequestParam Integer doctorId, @RequestBody DemoDoctor doctor) throws HttpStatus401Exception{
-
if(null == doctorId || null == doctor){
-
throw new HttpStatus401Exception("修改醫生信息失敗","DT3391","id不能爲空","請修改");
-
-
-
throw new HttpStatus401Exception("醫生不存在","DT3392","錯誤的ID","請更換ID");
-
-
System.
out.println(doctorId);
-
System.
out.println(doctor);
-
-
-
-
-
-
-
-
-
-
-
@RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.GET )
-
@ApiOperation(value="獲取醫生詳細信息", notes="僅返回姓名..")
-
@ApiImplicitParam(paramType="query", name = "doctorId", value = "醫生ID", required = true, dataType = "Integer")
-
public DemoDoctor getDoctorDetail(@RequestParam Integer doctorId) throws HttpStatus401Exception{
-
System.
out.println(doctorId);
-
-
throw new HttpStatus401Exception("查看醫生信息失敗","DT3390","未知緣由","請聯繫管理員");
-
-
-
throw new HttpStatus401Exception("醫生不存在","DT3392","錯誤的ID","請更換ID");
-
-
DemoDoctor doctor =
new DemoDoctor();
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@RequestMapping(value="/doctor", method= RequestMethod.GET )
-
@ApiOperation(value="獲取醫生列表", notes="目前一次所有取,不分頁")
-
-
@ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
-
@ApiImplicitParam(paramType="query", name = "pageIndex", value = "當前頁數", required = false, dataType = "String"),
-
@ApiImplicitParam(paramType="query", name = "pageSize", value = "每頁記錄數", required = true, dataType = "String"),
-
-
public PageInfo<DemoDoctor> getDoctorList(@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
-
@RequestParam(value = "pageSize", required = false) Integer pageSize,
-
HttpServletRequest request) throws HttpStatus401Exception{
-
-
String token = request.getHeader(
"token");
-
-
throw new HttpStatus401Exception("沒有權限","SS8888","沒有權限","請查看操做文檔");
-
-
-
throw new HttpStatus401Exception("每頁記錄數不粗安在","DT3399","不存在pageSize","請查看操做文檔");
-
-
-
DemoDoctor doctor1 =
new DemoDoctor();
-
-
doctor1.setName(
"測試員1");
-
DemoDoctor doctor2 =
new DemoDoctor();
-
-
doctor2.setName(
"測試員2");
-
-
List<DemoDoctor> doctorList =
new ArrayList<DemoDoctor>();
-
-
-
return new PageInfo<DemoDoctor>(doctorList);
-
-
-
-
增長header:
如今不少請求須要在header增長額外參數,能夠參考getDoctorList()的作法,使用request接收。
原文連接:https://blog.csdn.net/sanyaoxu_2/article/details/80555328