1. 程式人生 > 實用技巧 >介面文件(採用Swagger框架)

介面文件(採用Swagger框架)

傳統的介面文件(版本迭代時,介面文件有可能沒有更新),所以採用swagger框架,可以通過註解的方式來生成文件

開發中,可以將需求文件、資料庫、介面文件等放在test測試目錄resource下,工程打包時,並不會打包test目錄下的檔案

swagger資料夾
controller層上的註解生成文件案例
package cn.kooun.controller;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import cn.kooun.common.ResponseUtil;
import cn.kooun.common.check.CheckUtil;
import cn.kooun.common.result.ResultInfo;
import cn.kooun.service.base.MsgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * swagger控制層案例
 */
@RestController
//介面模組描述
@Api(tags = "swagger演示模組")
@RequestMapping("/swaggerDemo")
public class SwaggerDemoContrller {
	
	@Autowired
	private MsgService msgService;
	/**
	 * 表單請求案例
	 * @param userId
	 * @param code
	 * @return
	 */
	//value=介面名稱, notes=介面描述
	@ApiOperation(value = "表單請求案例", notes = "請求使用表單請求")
	@PostMapping("/demoQuery")
	@ApiImplicitParams({
		//paramType=引數請求型別 (query=表單請求,body=json請求)
		//name = 引數名稱
		//value = 引數名稱描述
		@ApiImplicitParam(name="userId",value="使用者id",paramType="query"),
		@ApiImplicitParam(name="code",value="驗證碼",paramType="query")
		})
	@ApiResponses({
		@ApiResponse(code=200,message=ResultInfo.COMMON_JSON),})
	public Object demoQuery(
			HttpServletRequest request,
			@ApiParam()String userId,
			String code) {
		//返回測試資料
		if(CheckUtil.checkDebugRsponse(request)) {
			//從t_debug_response表中獲取json格式資料
			return JSON.parse(msgService.getDebugResponse(1L));
		}
		return ResponseUtil.success();
	}
	
	/**
	 * json請求案例
	 * @param user
	 * @return
	 */
	@ApiOperation(value = "json請求案例", notes = "請求使用json請求")
	@PostMapping("/demoJson")
	@ApiImplicitParams({
		@ApiImplicitParam(name="userId",value="使用者id",required=true,paramType="body"),
		@ApiImplicitParam(name="userName",value="使用者名稱稱",paramType="body")
		})
	@ApiResponses({
		@ApiResponse(code=200,message=ResultInfo.COMMON_JSON),})
	public Object demoJson(HttpServletRequest request, @RequestBody User user) {
		System.out.println(user);
		//返回測試資料
		if(CheckUtil.checkDebugRsponse(request)) {
			return JSON.parse("{\r\n" + 
					"  'result': '業務結果',\r\n" + 
					"  'message': '彈窗訊息',\r\n" + 
					"  'status': '響應狀態',\r\n" + 
					"  'target': '錯誤提示',\r\n" + 
					"  'jump': '跳轉頁面'\r\n" + 
					"}");
		}
		return ResponseUtil.success();
	}
	public static void main(String[] args) {
		System.out.println(JSON.toJSONString(ResponseUtil.error("錯誤原因")));
	}
}



/**
 * model
 * @author chenwei
 * @date 2019年6月25日 下午5:29:54
 */
class User implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 306021471164575961L;
	private String userId;
	private String userName;
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	@Override
	public String toString() {
		return "User [userId=" + userId + ", userName=" + userName + "]";
	}
	
	
}
自定義請求介面引數上的註解生成文件案例
package cn.kooun.pojo.request;

import java.util.Date;

import javax.persistence.Table;

import cn.kooun.pojo.base.Uuid_IDDate;
import io.swagger.annotations.ApiModelProperty;
/**
 * 請求引數封裝案例
 * @author chenwei
 * @date 2019年8月2日 下午3:12:54
 */
public class RequestModel {

	@ApiModelProperty(value="商家Id",name="suserid",required=true)
	private String suserid;
	
	@ApiModelProperty(value="分類Id",name="goodstypeid",required=true)
    private String goodstypeid;
	
	@ApiModelProperty(value="商品名稱",name="suserid",required=true)
    private String goodsname;
	
	@ApiModelProperty(value="商品名稱小寫狀態",hidden=true)
    private String goodsnameIndex;
	
	@ApiModelProperty(value="計算單位",name="unittype",required=true)
    private Integer unittype;
	
	@ApiModelProperty(value="單價",name="unitprice",required=true)
    private String unitprice;
	
	@ApiModelProperty(value="待售數量",name="count",required=true)
    private String count;
	
	@ApiModelProperty(value="是否特色優品 0=否 1=是",name="superiorstatus",required=true)
    private Integer superiorstatus;
	
	@ApiModelProperty(value="特色優品是否錯選 0=否 1=是",name="issuperror",required=true)
    private Integer issuperror;
	
	@ApiModelProperty(value="商品圖片",name="pic")
    private String pic;
	
	@ApiModelProperty(value="商品簡介/促銷廣告",name="introduce")
    private String introduce;
	
	@ApiModelProperty(value="狀態 0=下架 1=上架",name="status",required=true)
    private Integer status;
	
	@ApiModelProperty(value="上架時間",example="2019-06-27 16:56:00",name="upframeTime")
    private Date upframeTime;
	
	@ApiModelProperty(value="下架時間",example="2019-06-27 16:56:00",name="downframeTime")
    private Date downframeTime;


   
    public String getSuserid() {
        return suserid;
    }

    public void setSuserid(String suserid) {
        this.suserid = suserid;
    }

    public String getGoodstypeid() {
        return goodstypeid;
    }

    public void setGoodstypeid(String goodstypeid) {
        this.goodstypeid = goodstypeid;
    }

    public String getGoodsname() {
        return goodsname;
    }

    public void setGoodsname(String goodsname) {
        this.goodsname = goodsname;
    }

    public String getGoodsnameIndex() {
        return goodsnameIndex;
    }

    public void setGoodsnameIndex(String goodsnameIndex) {
        this.goodsnameIndex = goodsnameIndex;
    }

    public Integer getUnittype() {
        return unittype;
    }

    public void setUnittype(Integer unittype) {
        this.unittype = unittype;
    }

    public String getUnitprice() {
        return unitprice;
    }

    public void setUnitprice(String unitprice) {
        this.unitprice = unitprice;
    }

    public String getCount() {
        return count;
    }

    public void setCount(String count) {
        this.count = count;
    }

    public Integer getSuperiorstatus() {
        return superiorstatus;
    }

    public void setSuperiorstatus(Integer superiorstatus) {
        this.superiorstatus = superiorstatus;
    }

    public Integer getIssuperror() {
        return issuperror;
    }

    public void setIssuperror(Integer issuperror) {
        this.issuperror = issuperror;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

    public String getIntroduce() {
        return introduce;
    }

    public void setIntroduce(String introduce) {
        this.introduce = introduce;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Date getUpframeTime() {
        return upframeTime;
    }

    public void setUpframeTime(Date upframeTime) {
        this.upframeTime = upframeTime;
    }

    public Date getDownframeTime() {
        return downframeTime;
    }

    public void setDownframeTime(Date downframeTime) {
        this.downframeTime = downframeTime;
    }


}
main下配置swagger
package cn.kooun.core.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;

import cn.kooun.common.ip.IpUtil;
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;

/**
 * 	swagger配置類
 *
 */
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class Swagger2Config implements WebMvcConfigurer {

	/**
	 *
	 * 顯示swagger-ui.html文件展示頁,還必須注入swagger資源:
	 * 
	 * @param registry
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("swagger-ui.html")
				.addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("doc.html")
				.addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**")
				.addResourceLocations("classpath:/META-INF/resources/webjars/");
		
	}

	/**
	 * 載入swagger2
	 * 
	 * @return
	 */
	@Bean
    public Docket buildDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //掃描指定的包生成介面文件
                .apis(RequestHandlerSelectors.basePackage("cn.kooun.controller"))
                .paths(PathSelectors.any())
                .build();
    }
	@Value("${server.port}")
	private String serverPort;

	/**
	 * swaggerui頁面資料配置
	 * 文件訪問路徑
	 * http://<ip>:<port>/v2/api-docs
	 * 原版檢視訪問路徑
	 * http://<ip>:<port>/swagger-ui.html
	 * swagger-bootstrap-ui檢視
	 * http://<ip>:<port>/doc.html
	 * @return
	 */
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("xxx測試服務API")
				.description("空雲資訊科技有限公司@API"
						+ "<p>"
						+ "<font style='color:red'>"
						+ "如果需要獲取業務資料的註釋請在請求頭中新增以下引數"
						+ "debug=1"
						+ "</font>"
						+ "</p>")
				.termsOfServiceUrl("http://"+IpUtil.getLocalIP()+":" + serverPort)
				.version("1.0")
				.build();
		
	}

}
IpUtil類
package cn.kooun.common.ip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;


/**
 * IP工具類
 */
public class IpUtil {
	

	/**
	 * 此方法描述的是:獲得伺服器的IP地址
	 * 
	 * @author chenwei
	 * @date 2018年4月10日 上午10:50:50
	 * @return
	 */
	public static String getLocalIP() {
		String sIP = "";
		InetAddress ip = null;
		try {
			boolean bFindIP = false;
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				if (bFindIP) {
					break;
				}
				NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();

				Enumeration<InetAddress> ips = ni.getInetAddresses();
				while (ips.hasMoreElements()) {
					ip = (InetAddress) ips.nextElement();
					if (!ip.isLoopbackAddress() && ip.getHostAddress().matches("(\\d{1,3}\\.){3}\\d{1,3}")) {
						bFindIP = true;
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (null != ip) {
			sIP = ip.getHostAddress();
		}
		return sIP;
	}


}
執行

瀏覽器位址列輸入http://主機ip:埠號/swagger-ui.html

ctrl + h eclipse 的全文搜尋(查bug)