传统的接口文档(版本迭代时,接口文档有可能没有更新),所以采用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("{
" +
" 'result': '业务结果',
" +
" 'message': '弹窗消息',
" +
" 'status': '响应状态',
" +
" 'target': '错误提示',
" +
" 'jump': '跳转页面'
" +
"}");
}
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)