SpringBoot整合Swagger-UI

zhoubangbang1發表於2020-12-29

mymes專案全套學習教程連載中,關注公眾號第一時間獲取

mymes整合Swagger-UI實現API線上文件

swagger 是一款RESTFUL介面的文件線上自動生成+功能測試功能軟體。 本文通過講解mymes如何利用Swagger-UI來實現一份完善的線上API文件

Swagger-UI常用註解:

  • @Api:用於修飾Controller,生成Controller文件

  • @ApiOperation: 用於修飾是Controller中方法,生成介面方法相關文件資訊

  • @ApiParam: 用於修飾介面中引數,生成介面引數相關文件資訊

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

新增Swagger-UI專案依賴

在pom.xml在新增 Swagger-UI相關依賴 --之前的依賴項可能出現bug把下面依賴對應替換

   <!--MyBatis分頁外掛-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
        </dependency>
        <!--整合druid連線池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!-- MyBatis 生成器 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>
        <!--Mysql資料庫驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.10</version>
        </dependency>
        <!--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>

        <!--Hutool Java工具包-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.5.7</version>
        </dependency>
        <dependency>
            <groupId>jakarta.validation</groupId>
            <artifactId>jakarta.validation-api</artifactId>
            <version>2.0.2</version>
        </dependency>

新增Swagger-UI配置

在config檔案下新增swagger-ui的java配置檔案

注: Swagger對生成的API文件範圍有三種不同選擇

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

  • 生成有指定註解的類的API文件

  • 生成有指定註解的方法的API文件

package com.cn.mymes.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 MymesSwaggerConfig {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //為當前包下controller生成API文件
                .apis(RequestHandlerSelectors.basePackage("com.cn.mymes.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("mymes的SwaggerUI演示")
                .description("mymes")
                .contact("mymes")
                .version("1.0")
                .build();
    }
}

修改MyBatis Generator註釋的生成規則

MyMesCommentGenerator為MyBatis Generator的自定義註釋生成器,修改addFieldComment方法使其生成Swagger的@ApiModelProperty註解來取代原來的方法註釋,新增addJavaFileComment方法,使其能在import中匯入@ApiModelProperty,否則需要手動匯入該類,在需要生成大量實體類時,是一件非常麻煩的事。

package com.cn.mymes.mgb;

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;

/**
 * 自定義註釋生成器
 */
public class MyMesCommentGenerator 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));
        }
    }
}

執行程式碼生成器重新生成mbg包中的程式碼

執行com.cn.mymes.mgb.MyMesGenerator,重新生成mbg中的程式碼,可以看到PmsBrand類中已經自動根據資料庫註釋新增了@ApiModelProperty註解

 

新增MyMes的Service介面

package com.cn.mymes.service;


import com.cn.mymes.mgb.model.MesBrand;

import java.util.List;


/**
 * PmsBrandService
 *
 */
public interface MyMesBrandService {
    List<MesBrand> listAllBrand();

    int createBrand(MesBrand brand);

    int updateBrand(Long id, MesBrand brand);

    int deleteBrand(Long id);

    List<MesBrand> listBrand(int pageNum, int pageSize);

    MesBrand getBrand(Long id);
}

實現MyMes的Service介面

package com.cn.mymes.service.impl;


import com.cn.mymes.mgb.mapper.MesBrandMapper;
import com.cn.mymes.mgb.model.MesBrand;
import com.cn.mymes.mgb.model.MesBrandExample;
import com.cn.mymes.service.MyMesBrandService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * MyMesBrandService的實現類
 */
@Service
public class MyMesBrandServiceImpl implements MyMesBrandService {
    @Autowired
    private MesBrandMapper  mesBrandMapper;

    @Override
    public List<MesBrand> listAllBrand() {
        return mesBrandMapper.selectByExample(new MesBrandExample());
    }

    @Override
    public int createBrand(MesBrand brand) {
        return mesBrandMapper.insertSelective(brand);
    }

    @Override
    public int updateBrand(Long id, MesBrand brand) {
        brand.setId(id);
        return mesBrandMapper.updateByPrimaryKeySelective(brand);
    }

    @Override
    public int deleteBrand(Long id) {
        return mesBrandMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<MesBrand> listBrand(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return mesBrandMapper.selectByExample(new MesBrandExample());
    }

    @Override
    public MesBrand getBrand(Long id) {
        return mesBrandMapper.selectByPrimaryKey(id);
    }
}

實現MyMesBrandController並新增Swagger註解

package com.cn.mymes.controller;


import com.cn.mymes.common.CommonPage;
import com.cn.mymes.common.CommonResult;
import com.cn.mymes.mgb.model.MesBrand;
import com.cn.mymes.service.MyMesBrandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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;

/**
 * MES品牌管理Controller
 *
 */
@Api(tags = "MyMesBrandController", description = "商品品牌管理")
@Controller
@RequestMapping("/brand")
public class MyMesBrandController {
    @Autowired
    private MyMesBrandService brandService;


    @ApiOperation("獲取所有品牌列表")
    @RequestMapping(value = "listAll", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<MesBrand>> getBrandList() {
        return CommonResult.success(brandService.listAllBrand());
    }

    @ApiOperation("新增品牌")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult createBrand(@RequestBody MesBrand pmsBrand) {
        CommonResult commonResult;
        int count = brandService.createBrand(pmsBrand);
        if (count == 1) {
            commonResult = CommonResult.success(pmsBrand);

        } else {
            commonResult = CommonResult.failed("操作失敗");
        }
        return commonResult;
    }

    @ApiOperation("更新指定id品牌資訊")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody MesBrand pmsBrandDto, BindingResult result) {
        CommonResult commonResult;
        int count = brandService.updateBrand(id, pmsBrandDto);
        if (count == 1) {
            commonResult = CommonResult.success(pmsBrandDto);

        } else {
            commonResult = CommonResult.failed("操作失敗");

        }
        return commonResult;
    }

    @ApiOperation("刪除指定id的品牌")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult deleteBrand(@PathVariable("id") Long id) {
        int count = brandService.deleteBrand(id);
        if (count == 1) {

            return CommonResult.success(null);
        } else {

            return CommonResult.failed("操作失敗");
        }
    }

    @ApiOperation("分頁查詢品牌列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<MesBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1")
                                                        @ApiParam("頁碼") Integer pageNum,
                                                        @RequestParam(value = "pageSize", defaultValue = "3")
                                                        @ApiParam("每頁數量") Integer pageSize) {
        List<MesBrand> brandList = brandService.listBrand(pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(brandList));
    }

    @ApiOperation("獲取指定id的品牌詳情")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<MesBrand> brand(@PathVariable("id") Long id) {
        return CommonResult.success(brandService.getBrand(id));
    }
}

執行專案,檢視結果

介面地址:http://localhost:9999/swagger-ui.html

1

 

公眾號

 

相關文章