一、Swagger-UI
Swagger-UI是HTML, Javascript, CSS的一个集合,可以动态地根据注解生成在线API文档。
二、常用注解
- @Api()用于类;用于修饰Controller类,生成Controller相关文档信息
表示标识这个类是swagger的资源
tags–表示说明
value–也是说明,可以使用tags替代
但是tags如果有多个值,会生成多个list
- @ApiOperation()用于方法;用于修饰Controller类中的方法,生成接口方法相关文档信息
表示一个http请求的操作
value用于方法描述
notes用于提示内容
tags可以重新分组(视情况而用)
- @ApiParam()用于方法,参数,字段说明;用于修饰接口中的参数,生成接口参数相关文档信息
表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填
- @ApiModel()用于类
表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
- @ApiModelProperty()用于方法,字段;用于修饰实体类的属性,当实体类是请求参数或返回结果时,直接生成相关文档信息
表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
- @ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略
- @ApiImplicitParam() 用于方法
表示单独的请求参数
- @ApiImplicitParams() 用于方法
包含多个 @ApiImplicitParam
name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
example–举例说明
三、整合Swagger-UI
1、添加依赖库
在pom.xml文件中添加Swagger-UI的相关依赖
<!--Swagger-UI API文档生产工具-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2、添加Swagger-UI的Java配置文件
Swagger对生成API文档的范围有三种不同的选择
- 生成指定包下面的类的API文档
- 生成有指定注解的类的API文档
- 生成有指定注解的方法的API文档
package com.macro.mall.tiny.config;
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;
/**
* Swagger2API文档的配置
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包下controller生成API文档
.apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
//为有@Api注解的Controller生成API文档
// .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
//为有@ApiOperation注解的方法生成API文档
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SwaggerUI演示")
.description("mall-tiny")
.contact("xiaoming")
.version("1.0")
.build();
}
}
3、给Controller添加上Swagger注解
package com.macro.mall.tiny.controller
import com.macro.mall.tiny.mbg.model.PmsBrand;
import com.macro.mall.tiny.service.PmsBrandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 品牌管理Controller
* Created by macro on 2019/4/19.
*/
@Api(tags = "PmsBrandController", description = "商品品牌管理")
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
@Autowired
private PmsBrandService brandService;
private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);
@ApiOperation("获取所有品牌列表")
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<PmsBrand>> getBrandList() {
return null;
}
@ApiOperation("添加品牌")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
return null;
}
@ApiOperation("更新指定id品牌信息")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody PmsBrand pmsBrandDto, BindingResult result) {
return null;
}
@ApiOperation("删除指定id的品牌")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult deleteBrand(@PathVariable("id") Long id) {
return null;
}
@ApiOperation("分页查询品牌列表")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1")
@ApiParam("页码") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "3")
@ApiParam("每页数量") Integer pageSize) {
List<PmsBrand> brandList = brandService.listBrand(pageNum, pageSize);
return null;
}
@ApiOperation("获取指定id的品牌详情")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<PmsBrand> brand(@PathVariable("id") Long id) {
return null;
}
}
4、 修改MyBatis Generator注释生成规则
package com.macro.mall.tiny.mbg;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.Properties;
/**
* 自定义注释生成器
* Created by macro on 2018/4/26.
*/
public class CommentGenerator extends DefaultCommentGenerator {
private boolean addRemarkComments = false;
private static final String EXAMPLE_SUFFIX="Example";
private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";
/**
* 设置用户配置的参数
*/
@Override
public void addConfigurationProperties(Properties properties) {
super.addConfigurationProperties(properties);
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
}
/**
* 给字段添加注释
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
String remarks = introspectedColumn.getRemarks();
//根据参数和备注信息判断是否添加备注信息
if(addRemarkComments&&StringUtility.stringHasValue(remarks)){
// addFieldJavaDoc(field, remarks);
//数据库中特殊字符需要转义
if(remarks.contains("\"")){
remarks = remarks.replace("\"","'");
}
//给model的字段添加swagger注解
field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
}
}
/**
* 给model的字段添加注释
*/
private void addFieldJavaDoc(Field field, String remarks) {
//文档注释开始
field.addJavaDocLine("/**");
//获取数据库字段的备注信息
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
for(String remarkLine:remarkLines){
field.addJavaDocLine(" * "+remarkLine);
}
addJavadocTag(field, false);
field.addJavaDocLine(" */");
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
super.addJavaFileComment(compilationUnit);
//只在model中添加swagger注解类的导入
if(!compilationUnit.isJavaInterface()&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){
compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
}
}
}
5、运行代码生成器重新生成model类
运行com.macro.mall.tiny.mbg.Generator的main方法,重新生成mbg中的代码,可以看到PmsBrand类中已经自动根据数据库注释添加了@ApiModelProperty注解
package com.macro.mall.tiny.mbg.model;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
public class PmsBrand implements Serializable {
private Long id;
private String name;
@ApiModelProperty(value = "首字母")
private String firstLetter;
private Integer sort;
@ApiModelProperty(value = "是否为品牌制造商:0->不是;1->是")
private Integer factoryStatus;
private Integer showStatus;
@ApiModelProperty(value = "产品数量")
private Integer productCount;
@ApiModelProperty(value = "产品评论数量")
private Integer productCommentCount;
@ApiModelProperty(value = "品牌logo")
private String logo;
@ApiModelProperty(value = "专区大图")
private String bigPic;
@ApiModelProperty(value = "品牌故事")
private String brandStory;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstLetter() {
return firstLetter;
}
public void setFirstLetter(String firstLetter) {
this.firstLetter = firstLetter;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getFactoryStatus() {
return factoryStatus;
}
public void setFactoryStatus(Integer factoryStatus) {
this.factoryStatus = factoryStatus;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Integer getProductCount() {
return productCount;
}
public void setProductCount(Integer productCount) {
this.productCount = productCount;
}
public Integer getProductCommentCount() {
return productCommentCount;
}
public void setProductCommentCount(Integer productCommentCount) {
this.productCommentCount = productCommentCount;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getBigPic() {
return bigPic;
}
public void setBigPic(String bigPic) {
this.bigPic = bigPic;
}
public String getBrandStory() {
return brandStory;
}
public void setBrandStory(String brandStory) {
this.brandStory = brandStory;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", firstLetter=").append(firstLetter);
sb.append(", sort=").append(sort);
sb.append(", factoryStatus=").append(factoryStatus);
sb.append(", showStatus=").append(showStatus);
sb.append(", productCount=").append(productCount);
sb.append(", productCommentCount=").append(productCommentCount);
sb.append(", logo=").append(logo);
sb.append(", bigPic=").append(bigPic);
sb.append(", brandStory=").append(brandStory);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
6、访问Swagger-UI接口文档地址
接口地址:http://localhost:8080/swagger-ui.html
可以看到接口列表,以及请求参数,返回响应参数