mall整合Swagger-UI實如今線API文檔

本文主要講解mall是如何經過整合Swagger-UI來實現一份至關完善的在線API文檔的。html

項目使用框架介紹

Swagger-UI

Swagger-UI是HTML, Javascript, CSS的一個集合,能夠動態地根據註解生成在線API文檔。java

經常使用註解

  • @Api:用於修飾Controller類,生成Controller相關文檔信息web

  • @ApiOperation:用於修飾Controller類中的方法,生成接口方法相關文檔信息spring

  • @ApiParam:用於修飾接口中的參數,生成接口參數相關文檔信息數據庫

  • @ApiModelProperty:用於修飾實體類的屬性,當實體類是請求參數或返回結果時,直接生成相關文檔信息api

整合Swagger-UI

添加項目依賴

在pom.xml中新增Swagger-UI相關依賴mybatis

<!--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>

添加Swagger-UI的配置

添加Swagger-UI的Java配置文件app

注意:Swagger對生成API文檔的範圍有三種不一樣的選擇框架

  • 生成指定包下面的類的API文檔dom

  • 生成有指定註解的類的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

對請求參數已經添加說明

對返回結果已經添加說明

圖片

直接在在線文檔上面進行接口測試

圖片

圖片

相關文章
相關標籤/搜索