• springboot(9) 整合Swagger-UI


    Swagger-UI可以生成动态的API文档,方便调试测试

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

    • 生成指定包下面的类的API文档
    • 生成有指定注解的类的API文档
    • 生成有指定注解的方法的API文档

    当生成指定包下面的类的API文档时,controller中没有加注释的请求接口也会生成API

    一. springboot中使用swagger

    1.pom.xml

    <!--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文档API配置类

    /**
     * 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.yy.mallTiny.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("macro")
                    .version("1.0")
                    .build();
        }
    }

    3.增加标签注释

    @Api @ApiOperation @ApiModelProperty
    @Api(tags = "PmsBrandController", value = "商品品牌管理")
    @Controller
    @RequestMapping("/brand")
    public class PmsBrandController {
        @Autowired
        PmsBrandService brandService;
    
        @ApiOperation("分页查询品牌列表")
        @RequestMapping(value = "page", method = RequestMethod.GET)
        @ResponseBody
        public CommonResult<CommonPage<PmsBrand>> getPageBrand(int pageNum, int pageSize){
            PageInfo<PmsBrand> pageInfo = brandService.listBrand(pageNum, pageSize);
            return CommonResult.success(CommonPage.restPage(pageInfo), "success");
        }
    // 没有swagger注释也会生成API
      @RequestMapping(value = "list", method = RequestMethod.GET)
      @ResponseBody
      public CommonResult<CommonPage<PmsBrand>> list(int pageNum, int pageSize){
      PageInfo<PmsBrand> pageInfo = brandService.listBrand(pageNum, pageSize);
      return CommonResult.success(CommonPage.restPage(pageInfo), "success");
      }
    }
    public class PmsBrand {
        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;

    运行项目, 访问http://localhost:8080/swagger-ui.html

     可以直接发请求,测试接口,

     还可以看到对返回参数的注释

     二。mybatis生成带@ApiModelProperty注释的model

    1.自定义注释生成器

    /**
     * 自定义注释生成器
     * 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));
            }
        }
    }

    2.mybatis-generator.xml中增加生成注释

    <context id="DB2Tables"    targetRuntime="MyBatis3">
            <!--生成mapper.xml时覆盖原文件-->
            <!--<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />-->
            <!--可以自定义生成model的代码注释-->
            <commentGenerator type="com.yy.mallTiny.mybatisGenerator.CommentGenerator">
                <!-- 是否去除自动生成的注释 true:是 : false:否 -->
                <property name="suppressAllComments" value="true"/>
                <property name="suppressDate" value="true"/>
                <property name="addRemarkComments" value="true"/>
            </commentGenerator>

    3.生成mybatis generator的类

    使用 mvn mybatis-generator:generate 直接生成会报错,

    [ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli) on project mall-tiny: Execution default-cli of goa
    l org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate failed: Cannot instantiate object of type com.yy.mallTiny.mybatisGenerator.CommentGenerator

    所以使用代码来生成

    /**
     * 用于生产MBG的代码
     * Created by macro on 2018/4/26.
     */
    public class Generator {
        public static void main(String[] args) throws Exception {
            //MBG 执行过程中的警告信息
            List<String> warnings = new ArrayList<String>();
            //当生成的代码重复时,覆盖原代码
            boolean overwrite = true;
            //读取我们的 MBG 配置文件
            InputStream is = Generator.class.getResourceAsStream("/mybatis-generator.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(is);
            is.close();
    
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            //创建 MBG
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            //执行生成代码
            myBatisGenerator.generate(null);
            //输出警告信息
            for (String warning : warnings) {
                System.out.println(warning);
            }
        }
    }

    执行main方法就能看到生成的model中有注释了

  • 相关阅读:
    软件测试入门知识
    QTP小应用一则
    频分时分波分码分
    解析UML9种图的作用
    OSI七层模型
    暑期实习心得
    0724工作小结 SQL查库是重点
    0723脚本存储过程的学习
    0722工作日志
    工作之余回味了曾经的写过的小说
  • 原文地址:https://www.cnblogs.com/t96fxi/p/13273408.html
Copyright © 2020-2023  润新知