查看原文
其他

mall整合Swagger-UI实现在线API文档

梦想de星空 macrozheng 2020-08-20
来自专辑
mall学习教程(架构篇)

本文主要讲解mall是如何通过整合Swagger-UI来实现一份相当完善的在线API文档的。

项目使用框架介绍

Swagger-UI

Swagger-UI是HTML, Javascript, CSS的一个集合,可以动态地根据注解生成在线API文档。

常用注解

  • @Api:用于修饰Controller类,生成Controller相关文档信息

  • @ApiOperation:用于修饰Controller类中的方法,生成接口方法相关文档信息

  • @ApiParam:用于修饰接口中的参数,生成接口参数相关文档信息

  • @ApiModelProperty:用于修饰实体类的属性,当实体类是请求参数或返回结果时,直接生成相关文档信息

整合Swagger-UI

添加项目依赖

在pom.xml中新增Swagger-UI相关依赖

  1. <!--Swagger-UI API文档生产工具-->

  2. <dependency>

  3. <groupId>io.springfox</groupId>

  4. <artifactId>springfox-swagger2</artifactId>

  5. <version>2.7.0</version>

  6. </dependency>

  7. <dependency>

  8. <groupId>io.springfox</groupId>

  9. <artifactId>springfox-swagger-ui</artifactId>

  10. <version>2.7.0</version>

  11. </dependency>

添加Swagger-UI的配置

添加Swagger-UI的Java配置文件

注意:Swagger对生成API文档的范围有三种不同的选择

  • 生成指定包下面的类的API文档

  • 生成有指定注解的类的API文档

  • 生成有指定注解的方法的API文档

  1. package com.macro.mall.tiny.config;


  2. import org.springframework.context.annotation.Bean;

  3. import org.springframework.context.annotation.Configuration;

  4. import springfox.documentation.builders.ApiInfoBuilder;

  5. import springfox.documentation.builders.PathSelectors;

  6. import springfox.documentation.builders.RequestHandlerSelectors;

  7. import springfox.documentation.service.ApiInfo;

  8. import springfox.documentation.spi.DocumentationType;

  9. import springfox.documentation.spring.web.plugins.Docket;

  10. import springfox.documentation.swagger2.annotations.EnableSwagger2;


  11. /**

  12. * Swagger2API文档的配置

  13. */

  14. @Configuration

  15. @EnableSwagger2

  16. public class Swagger2Config {

  17. @Bean

  18. public Docket createRestApi(){

  19. return new Docket(DocumentationType.SWAGGER_2)

  20. .apiInfo(apiInfo())

  21. .select()

  22. //为当前包下controller生成API文档

  23. .apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))

  24. //为有@Api注解的Controller生成API文档

  25. // .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))

  26. //为有@ApiOperation注解的方法生成API文档

  27. // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

  28. .paths(PathSelectors.any())

  29. .build();

  30. }


  31. private ApiInfo apiInfo() {

  32. return new ApiInfoBuilder()

  33. .title("SwaggerUI演示")

  34. .description("mall-tiny")

  35. .contact("macro")

  36. .version("1.0")

  37. .build();

  38. }

  39. }

给PmsBrandController添加Swagger注解

给原有的品牌管理Controller添加上Swagger注解

  1. package com.macro.mall.tiny.controller;


  2. import com.macro.mall.tiny.common.api.CommonPage;

  3. import com.macro.mall.tiny.common.api.CommonResult;

  4. import com.macro.mall.tiny.mbg.model.PmsBrand;

  5. import com.macro.mall.tiny.service.PmsBrandService;

  6. import io.swagger.annotations.Api;

  7. import io.swagger.annotations.ApiOperation;

  8. import io.swagger.annotations.ApiParam;

  9. import org.slf4j.Logger;

  10. import org.slf4j.LoggerFactory;

  11. import org.springframework.beans.factory.annotation.Autowired;

  12. import org.springframework.stereotype.Controller;

  13. import org.springframework.validation.BindingResult;

  14. import org.springframework.web.bind.annotation.*;


  15. import java.util.List;



  16. /**

  17. * 品牌管理Controller

  18. * Created by macro on 2019/4/19.

  19. */

  20. @Api(tags = "PmsBrandController", description = "商品品牌管理")

  21. @Controller

  22. @RequestMapping("/brand")

  23. public class PmsBrandController {

  24. @Autowired

  25. private PmsBrandService brandService;


  26. private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);


  27. @ApiOperation("获取所有品牌列表")

  28. @RequestMapping(value = "listAll", method = RequestMethod.GET)

  29. @ResponseBody

  30. public CommonResult<List<PmsBrand>> getBrandList() {

  31. return CommonResult.success(brandService.listAllBrand());

  32. }


  33. @ApiOperation("添加品牌")

  34. @RequestMapping(value = "/create", method = RequestMethod.POST)

  35. @ResponseBody

  36. public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {

  37. CommonResult commonResult;

  38. int count = brandService.createBrand(pmsBrand);

  39. if (count == 1) {

  40. commonResult = CommonResult.success(pmsBrand);

  41. LOGGER.debug("createBrand success:{}", pmsBrand);

  42. } else {

  43. commonResult = CommonResult.failed("操作失败");

  44. LOGGER.debug("createBrand failed:{}", pmsBrand);

  45. }

  46. return commonResult;

  47. }


  48. @ApiOperation("更新指定id品牌信息")

  49. @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)

  50. @ResponseBody

  51. public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody PmsBrand pmsBrandDto, BindingResult result) {

  52. CommonResult commonResult;

  53. int count = brandService.updateBrand(id, pmsBrandDto);

  54. if (count == 1) {

  55. commonResult = CommonResult.success(pmsBrandDto);

  56. LOGGER.debug("updateBrand success:{}", pmsBrandDto);

  57. } else {

  58. commonResult = CommonResult.failed("操作失败");

  59. LOGGER.debug("updateBrand failed:{}", pmsBrandDto);

  60. }

  61. return commonResult;

  62. }


  63. @ApiOperation("删除指定id的品牌")

  64. @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)

  65. @ResponseBody

  66. public CommonResult deleteBrand(@PathVariable("id") Long id) {

  67. int count = brandService.deleteBrand(id);

  68. if (count == 1) {

  69. LOGGER.debug("deleteBrand success :id={}", id);

  70. return CommonResult.success(null);

  71. } else {

  72. LOGGER.debug("deleteBrand failed :id={}", id);

  73. return CommonResult.failed("操作失败");

  74. }

  75. }


  76. @ApiOperation("分页查询品牌列表")

  77. @RequestMapping(value = "/list", method = RequestMethod.GET)

  78. @ResponseBody

  79. public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1")

  80. @ApiParam("页码") Integer pageNum,

  81. @RequestParam(value = "pageSize", defaultValue = "3")

  82. @ApiParam("每页数量") Integer pageSize) {

  83. List<PmsBrand> brandList = brandService.listBrand(pageNum, pageSize);

  84. return CommonResult.success(CommonPage.restPage(brandList));

  85. }


  86. @ApiOperation("获取指定id的品牌详情")

  87. @RequestMapping(value = "/{id}", method = RequestMethod.GET)

  88. @ResponseBody

  89. public CommonResult<PmsBrand> brand(@PathVariable("id") Long id) {

  90. return CommonResult.success(brandService.getBrand(id));

  91. }

  92. }

修改MyBatis Generator注释的生成规则

CommentGenerator为MyBatis Generator的自定义注释生成器,修改addFieldComment方法使其生成Swagger的@ApiModelProperty注解来取代原来的方法注释,添加addJavaFileComment方法,使其能在import中导入@ApiModelProperty,否则需要手动导入该类,在需要生成大量实体类时,是一件非常麻烦的事。

  1. package com.macro.mall.tiny.mbg;


  2. import org.mybatis.generator.api.IntrospectedColumn;

  3. import org.mybatis.generator.api.IntrospectedTable;

  4. import org.mybatis.generator.api.dom.java.CompilationUnit;

  5. import org.mybatis.generator.api.dom.java.Field;

  6. import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;

  7. import org.mybatis.generator.internal.DefaultCommentGenerator;

  8. import org.mybatis.generator.internal.util.StringUtility;


  9. import java.util.Properties;


  10. /**

  11. * 自定义注释生成器

  12. * Created by macro on 2018/4/26.

  13. */

  14. public class CommentGenerator extends DefaultCommentGenerator {

  15. private boolean addRemarkComments = false;

  16. private static final String EXAMPLE_SUFFIX="Example";

  17. private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";


  18. /**

  19. * 设置用户配置的参数

  20. */

  21. @Override

  22. public void addConfigurationProperties(Properties properties) {

  23. super.addConfigurationProperties(properties);

  24. this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));

  25. }


  26. /**

  27. * 给字段添加注释

  28. */

  29. @Override

  30. public void addFieldComment(Field field, IntrospectedTable introspectedTable,

  31. IntrospectedColumn introspectedColumn) {

  32. String remarks = introspectedColumn.getRemarks();

  33. //根据参数和备注信息判断是否添加备注信息

  34. if(addRemarkComments&&StringUtility.stringHasValue(remarks)){

  35. // addFieldJavaDoc(field, remarks);

  36. //数据库中特殊字符需要转义

  37. if(remarks.contains("\"")){

  38. remarks = remarks.replace("\"","'");

  39. }

  40. //给model的字段添加swagger注解

  41. field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");

  42. }

  43. }


  44. /**

  45. * 给model的字段添加注释

  46. */

  47. private void addFieldJavaDoc(Field field, String remarks) {

  48. //文档注释开始

  49. field.addJavaDocLine("/**");

  50. //获取数据库字段的备注信息

  51. String[] remarkLines = remarks.split(System.getProperty("line.separator"));

  52. for(String remarkLine:remarkLines){

  53. field.addJavaDocLine(" * "+remarkLine);

  54. }

  55. addJavadocTag(field, false);

  56. field.addJavaDocLine(" */");

  57. }


  58. @Override

  59. public void addJavaFileComment(CompilationUnit compilationUnit) {

  60. super.addJavaFileComment(compilationUnit);

  61. //只在model中添加swagger注解类的导入

  62. if(!compilationUnit.isJavaInterface()&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){

  63. compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));

  64. }

  65. }

  66. }

运行代码生成器重新生成mbg包中的代码

运行com.macro.mall.tiny.mbg.Generator的main方法,重新生成mbg中的代码,可以看到PmsBrand类中已经自动根据数据库注释添加了@ApiModelProperty注解

运行项目,查看结果

访问Swagger-UI接口文档地址

接口地址:http://localhost:8080/swagger-ui.html

对请求参数已经添加说明

对返回结果已经添加说明

直接在在线文档上面进行接口测试

项目源码地址

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-02

推荐阅读



欢迎关注,点个在看

    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存