zoukankan      html  css  js  c++  java
  • 自定义swagger maven codegen插件

    项目中需要根据openapi 2.0接口定义自动生成指定框架代码,github中有对应的案例,不过生成的代码框架不符合当前需求,因此根据项目需要自定义了一个codegen插件,这里记录下插件流程

    swagger-codegen项目github地址:https://github.com/swagger-api/swagger-codegen

    maven插件编写过程

    1、IDEA创建maven-plugin工程

    2、指定packaging和artifactId

    maven插件packageing类型为maven-plugin,artifactId即为maven插件的命名,按照官方规范,maven插件命名建议为:xxxx-maven-plugin,这样命名有两个好处:

    (1)maven-xxxx-plugin为maven官方插件命名,使用这种命名方式可能侵权

    (2)自定义插件maven执行命令为mvn groupId:artifactId:goal,使用推荐命名方式,maven命令可以简化为mvn xxxx:goal

    3、继承AbstactMojo自定义Mojo类

    (1)@Mojo注解用来指定插件goalPrefix和执行的生命周期

    (2)@Parameter注解用来指定该插件输入参数

    (3)execute()方法用来编写maven插件逻辑

    4、maven工程依赖及注意事项

    (1)基础依赖

    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-plugin-api</artifactId>
        <version>3.6.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-project</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven.plugin-tools</groupId>
        <artifactId>maven-plugin-annotations</artifactId>
        <version>3.6.0</version>
    </dependency> <!--  Mojo类注解需要添加的依赖 -->

    (2)注意事项:如果插件Mojo类中使用的java8语法,需要在build标签中添加maven-plugin-plugin编译依赖,并且显式指定版本号为3.5.2及以上

    swagger-codegen流程

    1、添加swagger依赖

    <dependency>
        <groupId>io.swagger.parser.v3</groupId>
        <artifactId>swagger-parser</artifactId>
        <version>2.0.20</version>
    </dependency>
    <dependency>
        <groupId>io.swagger.codegen.v3</groupId>
        <artifactId>swagger-codegen</artifactId>
        <version>3.0.21</version>
    </dependency>

    2、定义mustache模板

    swagger提供了解析mustache模板文件的方法,通过解析yaml文件定义及mustache模板,生成指定的java类;

    mustache传送门:https://github.com/mustache/mustache.github.com

    举例:生成api接口类mustache模板

    package {{apiPackage}};
    
    {{#importPackageList}}
    import {{className}};{{/importPackageList}}
    import javax.servlet.ServletException;
    
    public interface {{className}}Api {
    {{#pathGetEntity}}
        {{pathGetEntity.responseType}} {{pathGetEntity.methodName}}({{#pathGetEntity.params}}{{paramType}} {{paramName}}{{/pathGetEntity.params}}) throws ServletException;
    {{/pathGetEntity}}{{#pathDeleteEntity}}
        void {{pathDeleteEntity.methodName}}({{#pathDeleteEntity.params}}{{paramType}} {{paramName}}{{/pathDeleteEntity.params}}) throws ServletException;
    {{/pathDeleteEntity}}{{#pathPostEntity}}
        void {{pathPostEntity.methodName}}({{#pathPostEntity.params}}{{paramType}} {{paramName}}{{/pathPostEntity.params}}) throws ServletException;
    {{/pathPostEntity}}{{#pathPutEntity}}
        void {{pathPutEntity.methodName}}({{#pathPutEntity.params}}{{paramType}} {{paramName}}{{/pathPutEntity.params}}) throws ServletException;
    {{/pathPutEntity}}
    }

    3、通过开源swagger解析yaml定义

    private Swagger createSwagger() throws MojoExecutionException {
        String apiFileStr;
        try {
            File file = new File(this.inputSpec);
            apiFileStr = FileUtils.readFileToString(file, StandardCharsets.UTF_8).trim();
        } catch (IOException e) {
            throw new MojoExecutionException("Read api file to string exception!");
        }
    
        return new SwaggerParser().parse(apiFileStr);
    }

    该swagger对象是基于openapi 2.0规范的解析对象,包含paths、definations等

    4、根据输入解析及mustache模板,生成对应的api接口类

    private void writeToFile(Object context, String fileName, String templateName) {
        try {
            // 获取模板信息
            String templateFileString = this.getTempFileString(templateName);
    
            // 生成模板
            Template template = Mustache.compiler().compile(templateFileString);
    
            // 解析模板
            String executeResult = template.execute(context);
    
            // 生成java类
            String outputPath = this.getOutputFilePath(fileName, templateName);
            FileUtils.writeStringToFile(new File(outputPath), executeResult, StandardCharsets.UTF_8, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    5、yaml定义及生成的api接口类

    swagger: "2.0"
    info:
      title: Title
      description: Title
      version: 1.0.0
    host: www
    schemes:
      - https
    basePath: /rest
    paths:
      /test/v1/user:
        post:
          tags:
            - "MyUser"
          summary: "创建用户"
          operationId: "createUser"
          produces:
            - "application/json"
          consumes:
            - "application/json"
          parameters:
            - name: "user"
              in: body
              description: "创建用户"
              required: true
              schema:
                $ref: '#/definitions/User'
          responses:
            200:
              description: "创建用户成功."
        put:
          tags:
            - "MyUser"
          summary: "修改用户"
          operationId: "modifyUser"
          produces:
            - "application/json"
          consumes:
            - "application/json"
          parameters:
            - name: "user"
              in: body
              description: "修改用户"
              required: true
              schema:
                $ref: '#/definitions/User'
          responses:
            200:
              description: "修改用户成功."
      /test/v1/user/{id}:
        delete:
          tags:
            - "MyUser"
          summary: "通过ID删除用户"
          operationId: "deleteUserById"
          produces:
            - "application/json"
          consumes:
            - "application/json"
          parameters:
            - name: "id"
              in: query
              description: "通过ID删除用户"
              required: true
              type: "integer"
              format: "int64"
          responses:
            200:
              description: "Delete family members by person id"
        get:
          tags:
            - "MyUser"
          summary: "通过ID获取用户信息"
          operationId: "getUserById"
          produces:
            - "application/json"
          consumes:
            - "application/json"
          parameters:
            - name: "id"
              in: query
              description: "通过ID获取用户信息"
              required: true
              type: "integer"
              format: "int64"
          responses:
            200:
              description: "Retrieves family members by person id"
              schema:
                $ref: '#/definitions/User'
    definitions:
      User:
        type: "object"
        required:
          - "id"
          - "firstName"
          - "lastName"
          - "dateOfBirth"
          - "gender"
        properties:
          id:
            type: "integer"
            format: "int64"
          firstName:
            type: "string"
            example: "John"
          lastName:
            type: "string"
            example: "Smith"
          dateOfBirth:
            type: "string"
            example: "1992-10-05"
    package com.demo.api;
    
    import com.demo.model.User;
    import javax.servlet.ServletException;
    
    public interface MyUserApi {
        User getUserById(Integer id) throws ServletException;
    
        void deleteUserById(Integer id) throws ServletException;
    
        void createUser(User user) throws ServletException;
    
        void modifyUser(User user) throws ServletException;
    }

    本文只是简单记录下通过swagger编写maven插件的过程,完整的代码见我的github

    swagger-codegen插件地址:https://github.com/bale1992/swagger-codegen-maven-plugin

    测试工程地址:https://github.com/bale1992/swagger-codegen-maven-plugin-test

  • 相关阅读:
    md5加密(4)
    生成短的uuid
    九九乘法
    闰年判断
    初识网络传输
    省选模拟77
    省选模拟76
    省选模拟75
    省选模拟74
    省选模拟73
  • 原文地址:https://www.cnblogs.com/sniffs/p/13461951.html
Copyright © 2011-2022 走看看