Swagger Codegen 自动生成Spring Boot代码

燕富
2023-12-01

Swagger Codegen是一个开源的代码生成器,根据Swagger定义的RESTful API可以自动建立服务端和客户端的连接。Swagger Codegen的源码可以在Github上找到。

GitHub: https://github.com/swagger-api/swagger-codegen

本文采用的是2.3.1版本,具体jar包可以在GitHub上下载。下边开始使用介绍

  1. 将swagger-codegen-cli-2.3.1.jar放在指定目录下,打开命令行工具,执行以下命令,目的是查看swagger-codegen支持的语言
    $ java -jar swagger-codegen-cli-2.3.1.jar
    Available languages: [ada, ada-server, akka-scala, android, apache2, apex, aspnetcore, bash, csharp, clojure, cwiki, cpprest, csharp-dotnet2, dart, elixir, elm, eiffel, erlang-client, erlang-server, finch, flash, python-flask, go, go-server, groovy, haskell-http-client, haskell, jmeter, jaxrs-cxf-client, jaxrs-cxf, java, inflector, jaxrs-cxf-cdi, jaxrs-spec, jaxrs, msf4j, java-pkmst, java-play-framework, jaxrs-resteasy-eap, jaxrs-resteasy, javascript, javascript-closure-angular, java-vertx, kotlin, lua, lumen, nancyfx, nodejs-server, objc, perl, php, powershell, pistache-server, python, qt5cpp, r, rails5, restbed, ruby, rust, rust-server, scala, scala-lagom-server, scalatra, scalaz, php-silex, sinatra, slim, spring, dynamic-html, html2, html, swagger, swagger-yaml, swift4, swift3, swift, php-symfony, tizen, typescript-aurelia, typescript-angular, typescript-angularjs, typescript-fetch, typescript-jquery, typescript-node, undertow, ze-ph]
    

    下图为执行命令后结果,可以发现,2.3.1版本已经支持了spring

  2. 运行以下命令,可以查看支持的命令

    $ java -jar swagger-codegen-cli-2.3.1.jar help
    usage: swagger-codegen-cli <command> [<args>]
    
    The most commonly used swagger-codegen-cli commands are:
        config-help   Config help for chosen lang
        generate      Generate code with chosen lang
        help          Display help information
        langs         Shows available langs
        meta          MetaGenerator. Generator for creating a new template set and configuration for Codegen.  The output will be based on the language you specify, and includes default templates to include.
        validate      Validate specification
        version       Show version information
    
    See 'swagger-codegen-cli help <command>' for more information on a specific
    command.
    

    3.查看spring配置文件参数含义

    $ java -jar swagger-codegen-cli-2.3.1.jar config-help -l spring
    
    CONFIG OPTIONS
            sortParamsByRequiredFlag
                Sort method arguments to place required parameters before optional parameters. (Default: true)
    
            ensureUniqueParams
                Whether to ensure parameter names are unique in an operation (rename parameters that are not). (Default: true)
    
            allowUnicodeIdentifiers
                boolean, toggles whether unicode identifiers are allowed in names or not, default is false (Default: false)
    
            modelPackage
                package for generated models
    
            apiPackage
                package for generated api classes
    
            invokerPackage
                root package for generated code
    
            groupId
                groupId in generated pom.xml
    
            artifactId
                artifactId in generated pom.xml
    
            artifactVersion
                artifact version in generated pom.xml
    
            artifactUrl
                artifact URL in generated pom.xml
    
            artifactDescription
                artifact description in generated pom.xml
    
            scmConnection
                SCM connection in generated pom.xml
    
            scmDeveloperConnection
                SCM developer connection in generated pom.xml
    
            scmUrl
                SCM URL in generated pom.xml
    
            developerName
                developer name in generated pom.xml
    
            developerEmail
                developer email in generated pom.xml
    
            developerOrganization
                developer organization in generated pom.xml
    
            developerOrganizationUrl
                developer organization URL in generated pom.xml
    
            licenseName
                The name of the license
    
            licenseUrl
                The URL of the license
    
            sourceFolder
                source folder for generated code
    
            localVariablePrefix
                prefix for generated code members and local variables
    
            serializableModel
                boolean - toggle "implements Serializable" for generated models (Default: false)
    
            bigDecimalAsString
                Treat BigDecimal values as Strings to avoid precision loss. (Default: false)
    
            fullJavaUtil
                whether to use fully qualified name for classes under java.util. This option only works for Java API client (Default: false)
    
            hideGenerationTimestamp
                hides the timestamp when files were generated
    
            withXml
                whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML) (Default: false)
    
            dateLibrary
                Option. Date library to use
                    joda - Joda (for legacy app only)
                    legacy - Legacy java.util.Date (if you really have a good reason not to use threetenbp
                    java8-localdatetime - Java 8 using LocalDateTime (for legacy app only)
                    java8 - Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets "java8" to true
                    threetenbp - Backport of JSR310 (preferred for jdk < 1.8)
    
            java8
                Option. Use Java8 classes instead of third party equivalents
                    true - Use Java 8 classes such as Base64
                    false - Various third party libraries as needed
    
            title
                server title name or client service name
    
            configPackage
                configuration package for generated code
    
            basePackage
                base package (invokerPackage) for generated code
    
            interfaceOnly
                Whether to generate only API interface stubs without the server files. (Default: false)
    
            delegatePattern
                Whether to generate the server files using the delegate pattern (Default: false)
    
            singleContentTypes
                Whether to select only one produces/consumes content-type by operation. (Default: false)
    
            java8
                use java8 default interface (Default: false)
    
            async
                use async Callable controllers (Default: false)
    
            responseWrapper
                wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)
    
            useTags
                use tags for creating interface and controller classnames (Default: false)
    
            useBeanValidation
                Use BeanValidation API annotations (Default: false)
    
            implicitHeaders
                Use of @ApiImplicitParams for headers. (Default: false)
    
            swaggerDocketConfig
                Generate Spring Swagger Docket configuration class. (Default: false)
    
            useOptional
                Use Optional container for optional parameters (Default: false)
    
            library
                library template (sub-template) to use (Default: spring-boot)
                    spring-boot - Spring-boot Server application using the SpringFox integration.
                    spring-mvc - Spring-MVC Server application using the SpringFox integration.
                    spring-cloud - Spring-Cloud-Feign client with Spring-Boot auto-configured settings.
    

    4.下边为我的配置文件内容,命名为config.json

    {
    "apiPackage": "com.manulife.ap.server.api",
    "artifactId": "cmp-performance-mgt-service",
    "basePackage": "com.manulife.ap.server",
    "configPackage": "com.manulife.ap.server.config",
    "dateLibrary": "java8",
    "delegatePattern": true,
    "groupId": "com.manulife.ap",
    "hideGenerationTimestamp": true,
    "java8": true,
    "language": "spring-boot",
    "modelPackage": "com.manulife.ap.server.model"
    }
    
    

    5.下图为swagger配置文件内容,通过 OpenAPI Specification 来描述 API,命名为openapi.yml

    swagger: '2.0'
    info:
      title: Performance API
      description: Performance API
      version: 1.0.0
    paths:
      /performance-mgt/v1/get-performance:
        get:
          tags:
          - performance
          operationId: getPerformance
          parameters:
          - name: agentId
            in: query
            type: string
            required: true
          - name: startDate
            in: query
            type: string
            required: true
          - name: endDate
            in: query
            type: string
          - name: zoneId
            in: query
            type: string
            default: +07:00
          responses:
            '200':
              description: OK
              schema:
                $ref: '#/definitions/GetPerformanceResponse'
            default:
              description: default
              schema:
                $ref: '#/definitions/ErrorResponse'
      /performance-mgt/v1.1/get-performance:
        get:
          tags:
          - performance
          operationId: getPerformanceV1.1
          parameters:
          - name: agentId
            in: query
            type: string
            required: true
          - name: startDate
            in: query
            type: string
            required: true
          - name: endDate
            in: query
            type: string
          - name: zoneId
            in: query
            type: string
            default: +07:00
          responses:
            '200':
              description: OK
              schema:
                $ref: '#/definitions/GetPerformanceSummaryResponse'
            default:
              description: default
              schema:
                $ref: '#/definitions/ErrorResponse'
      /performance-mgt/v1/get-performance-purpose-second-level:
        get:
          tags:
          - performanceSecondLevel
          operationId: getPerformancePurposeSecondLevel
          parameters:
          - name: agentId
            in: query
            type: string
            required: true
          - name: startDate
            in: query
            type: string
            required: true
          - name: endDate
            in: query
            type: string
          - name: purpose
            in: query
            type: string
          - name: zoneId
            in: query
            type: string
            default: GMT+7
          responses:
            '200':
              description: OK
              schema:
                $ref: '#/definitions/GetPerformanceSecondLevelPurposeResponse'
            default:
              description: default
              schema:
                $ref: '#/definitions/ErrorResponse'
      /performance-mgt/v1.2/get-performance-purpose-second-level:
        get:
          tags:
          - performanceSecondLevel
          operationId: getPerformancePurposeSecondLevelV1.2
          parameters:
          - name: agentId
            in: query
            type: string
            required: true
          - name: startDate
            in: query
            type: string
            required: true
          - name: endDate
            in: query
            type: string
          - name: purpose
            in: query
            type: string
          - name: zoneId
            in: query
            type: string
            default: +07:00
          responses:
            '200':
              description: OK
              schema:
                $ref: '#/definitions/GetPerformanceSecondLevelPurposeResponseV1.2'
            default:
              description: default
              schema:
                $ref: '#/definitions/ErrorResponse'
      /performance-mgt/v1/get-performance-lead-second-level:
        get:
          tags:
          - performanceSecondLevel
          operationId: getPerformanceLeadSecondLevel
          parameters:
          - name: agentId
            in: query
            type: string
            required: true
          - name: startDate
            in: query
            type: string
            required: true
          - name: endDate
            in: query
            type: string
          - name: purpose
            in: query
            type: string
          - name: zoneId
            in: query
            type: string
            default: +07:00
          responses:
            '200':
              description: OK
              schema:
                $ref: '#/definitions/GetPerformanceSecondLevelLeadResponse'
            default:
              description: default
              schema:
                $ref: '#/definitions/ErrorResponse'
      /performance-mgt/v1/get-production-bonus:
        get:
          tags:
          - bonus
          operationId: getProductionBonus
          parameters:
          - in: header
            name: X-User-ID
            type: string
            required: true
          - name: userId
            in: query
            type: string
          - name: joiningDate
            in: query
            type: string
            required: true
          - name: startDate
            in: query
            type: string
          - name: endDate
            in: query
            type: string
          responses:
            '200':
              description: OK
              schema:
                $ref: '#/definitions/GetBonusResponse'
            default:
              description: default
              schema:
                $ref: '#/definitions/ErrorResponse'
    definitions:
      GetBonusResponse:
        type: object
        properties:
          result:
            type: object
            properties:
              monthly:
                $ref: '#/definitions/MonthlyBonus'
              yearly:
                $ref: '#/definitions/MonthlyBonus'
          error:
            $ref: '#/definitions/ErrorResponse'
      MonthlyBonus:
        type: array
        items:
          properties:
            year:
              type: integer
            month:
              type: integer
            bonus:
              type: number
      GetPerformanceSecondLevelLeadResponse:
        type: object
        properties:
          result:
            type: object
            properties:
              startDate:
                type: string
              endDate:
                type: string
              purpose:
                type: string
              data:
                type: array
                items:
                  $ref: '#/definitions/Lead'
          error:
            $ref: '#/definitions/ErrorResponse'
      GetPerformanceSecondLevelPurposeResponse:
        type: object
        properties:
          result:
            type: object
            properties:
              startDate:
                type: string
              endDate:
                type: string
              purpose:
                type: string
              completed:
                type: array
                items:
                  $ref: '#/definitions/Activity'
              active:
                type: array
                items:
                  $ref: '#/definitions/Activity'
          error:
            $ref: '#/definitions/ErrorResponse'
      GetPerformanceSecondLevelPurposeResponseV1.2:
        type: object
        properties:
          result:
            type: object
            properties:
              startDate:
                type: string
              endDate:
                type: string
              purpose:
                type: string
              completed:
                type: array
                items:
                  $ref: '#/definitions/ActivityV1.2'
              active:
                type: array
                items:
                  $ref: '#/definitions/ActivityV1.2'
          error:
            $ref: '#/definitions/ErrorResponse'
      GetPerformanceSummaryResponse:
        type: object
        properties:
          result:
            type: object
            properties:
              summary:
                type: object
                properties:
                  dataByWeek:
                    type: array
                    items:
                      $ref: '#/definitions/WeeklySummaryPerformanceData'
                  dataByMonth:
                    type: array
                    items:
                      $ref: '#/definitions/MonthlySummaryPerformanceData'
                  dataYearToDate:
                    type: array
                    items:
                      $ref: '#/definitions/YearlySummaryPerformanceData'
          error:
            $ref: '#/definitions/ErrorResponse'
      GetPerformanceResponse:
        type: object
        properties:
          result:
            type: object
            properties:
              summary:
                type: object
                properties:
                  dataByMonth:
                    type: array
                    items:
                      $ref: '#/definitions/MonthlySummaryPerformanceData'
                  dataYearToDate:
                    type: array
                    items:
                      $ref: '#/definitions/YearlySummaryPerformanceData'
              data:
                type: object
                properties:
                  calls:
                    $ref: '#/definitions/PerformanceDataByPurpose'
                  closings:
                    $ref: '#/definitions/PerformanceDataByPurpose'
                  prospects:
                    $ref: '#/definitions/PerformanceDataByLeadType'
                  proposals:
                    $ref: '#/definitions/PerformanceDataByPurpose'
                  referrals:
                    $ref: '#/definitions/PerformanceDataByLeadType'
                  interviews:
                    $ref: '#/definitions/PerformanceDataByPurpose'
          error:
            $ref: '#/definitions/ErrorResponse'
      PerformanceDataByPurpose:
        type: array
        items:
          $ref: '#/definitions/PerformanceDataByPurposeByMonth'
      PerformanceDataByPurposeByMonth:
        type: object
        properties:
          month:
            type: string
            format: date
          details:
            type: array
            items:
              $ref: '#/definitions/PerformanceDataByPurposeByMonthByWeek'
      PerformanceDataByPurposeByMonthByWeek:
        type: object
        properties:
          week:
            type: integer
          startDate:
            type: string
            format: date
          endDate:
            type: string
            format: date
          weeklyPerformance:
            $ref: '#/definitions/PerformanceValues'
          monthlyPerformance:
            $ref: '#/definitions/PerformanceValues'
          items:
            type: array
            items:
              $ref: '#/definitions/Event'
      Event:
        type: object
        properties:
          id:
            type: integer
            format: int64
          startDateTime:
            type: string
            format: date-time
          type:
            type: string
          subject:
            type: string
          whoId:
            type: integer
            format: int64
          whoName:
            type: string
      Activity:
        type: object
        properties:
          leadId:
            type: integer
            format: int64
          activityId:
            type: integer
            format: int64
          subject:
            type: string
          purpose:
            type: string
            enum:
            - New Leads
            - Calls
            - Interviews
            - Proposal Presented
            - Closing
          startDateTime:
            type: string
            format: date-time
          endDateTime:
            type: string
            format: date-time
          location:
            type: string
            maxLength: 1000
          notes:
            type: string
            maxLength: 1000
          whoName:
            type: string
      ActivityV1.2:
        type: object
        properties:
          leadId:
            type: string
          activityId:
            type: string
          subject:
            type: string
          purpose:
            type: string
            enum:
            - New Leads
            - Calls
            - Interviews
            - Proposal Presented
            - Closing
          startDateTime:
            type: string
            format: date-time
          endDateTime:
            type: string
            format: date-time
          location:
            type: string
            maxLength: 1000
          notes:
            type: string
            maxLength: 1000
          whoName:
            type: string
          outcome:
            type: string
            enum:
            - agree_appointment
            - call_later
            - no_answer
            - denied
            - fact_finding
            - fna
            - considering
            - next_meeting_for_presenting_proposal
            - missed_appointment
            - adjust_the_proposal
            - objections
            - closing_completed_application_form
            - contract_submission
            - pending
            - contract_issued
            - contract_delivery
            - drop_rejected
          fyc:
            type: number
          fyp:
            type: number
          deliveryDate:
            type: string
            format: date
      PerformanceDataByLeadType:
        type: array
        items:
          $ref: '#/definitions/PerformanceDataByLeadTypeByMonth'
      PerformanceDataByLeadTypeByMonth:
        type: object
        properties:
          month:
            type: string
            format: date
          details:
            type: array
            items:
              $ref: '#/definitions/PerformanceDataByLeadTypeByMonthByWeek'
      PerformanceDataByLeadTypeByMonthByWeek:
        type: object
        properties:
          week:
            type: integer
          startDate:
            type: string
            format: date
          endDate:
            type: string
            format: date
          weeklyPerformance:
            $ref: '#/definitions/PerformanceValues'
          monthlyPerformance:
            $ref: '#/definitions/PerformanceValues'
          items:
            type: array
            items:
              $ref: '#/definitions/Lead'
      Lead:
        type: object
        properties:
          firstName:
            type: string
          lastName:
            type: string
          name:
            type: string
          leadSource:
            type: string
            enum:
            - Natural market
            - Personal observation
            - Referral
            - Social media
            - Orphan policyholder
            - Lead provided by Manulife
            - Cold call
            - Family or Friends
          age:
            type: string
            enum:
            - <= 25
            - 26 - 44
            - 45 - 64
            - '>=65'
          income:
            type: string
            enum:
            - <=10 million VND
            - 10 million to 20 million VND
            - 20 million to 30 million VND
            - '>=30 million VND'
          children:
            type: integer
            format: int32
            enum:
            - 1
            - 2
          maritalStatus:
            type: integer
            format: int32
            enum:
            - 1
            - 2
          familiarity:
            type: string
            enum:
            - Acquaintances
            - Familiar
            - Very Familiar
      MonthlySummaryPerformanceData:
        type: object
        properties:
          month:
            type: string
            format: date
          summaryDataByMonth:
            type: object
            properties:
              income:
                $ref: '#/definitions/Income'
              expectedBonus:
                $ref: '#/definitions/ExpectedBonus'
              callAppointments:
                $ref: '#/definitions/PerformanceValues'
              closings:
                $ref: '#/definitions/PerformanceValues'
              leads:
                $ref: '#/definitions/PerformanceValues'
              proposals:
                $ref: '#/definitions/PerformanceValues'
              referrals:
                $ref: '#/definitions/PerformanceValues'
              sales:
                $ref: '#/definitions/PerformanceValues'
      YearlySummaryPerformanceData:
        type: object
        properties:
          year:
            type: integer
          summaryDataByMonth:
            type: object
            properties:
              income:
                $ref: '#/definitions/Income'
              expectedBonus:
                $ref: '#/definitions/ExpectedBonus'
              callAppointments:
                $ref: '#/definitions/PerformanceValues'
              closings:
                $ref: '#/definitions/PerformanceValues'
              leads:
                $ref: '#/definitions/PerformanceValues'
              proposals:
                $ref: '#/definitions/PerformanceValues'
              referrals:
                $ref: '#/definitions/PerformanceValues'
              sales:
                $ref: '#/definitions/PerformanceValues'
      Income:
        type: object
        properties:
          targetIncome:
            type: number
          totalIncome:
            type: number
      ExpectedBonus:
        type: object
        properties:
          mdrtBonus:
            type: number
          newAgentBonus:
            type: number
          monthlyBonus:
            type: number
          quarterlyBonus:
            type: number
      WeeklySummaryPerformanceData:
        type: object
        properties:
          month:
            type: string
            format: date
          week:
            type: integer
          summaryDataByWeek:
            type: object
            properties:
              income:
                $ref: '#/definitions/Income'
              expectedBonus:
                $ref: '#/definitions/ExpectedBonus'
              callAppointments:
                $ref: '#/definitions/PerformanceValues'
              closings:
                $ref: '#/definitions/PerformanceValues'
              leads:
                $ref: '#/definitions/PerformanceValues'
              proposals:
                $ref: '#/definitions/PerformanceValues'
              referrals:
                $ref: '#/definitions/PerformanceValues'
              sales:
                $ref: '#/definitions/PerformanceValues'
      PerformanceValues:
        type: object
        properties:
          actual:
            type: integer
          expected:
            type: integer
          percentage:
            type: integer
      ErrorResponse:
        type: object
        description: Error Model if there is exception
        properties:
          errorCode:
            type: string
          errorMessage:
            type: object

    6.-i -c 分别制定相应的配置文件,-l制定语言,此处指定为spring,-o指定生成代码保存路径

    $ java -jar swagger-codegen-cli-2.3.1.jar  generate -i myswagger/swagger/openapi.yml  -c myswagger/swagger/config.json  -l spring  -o myswagger/test
    

    参考资料:https://www.jianshu.com/p/cdb41c9e52e2

 类似资料: