简体   繁体   中英

How do you have the maven swagger codegen plugin generate Java classes using inheritance?

In our swagger.yaml file, we have a definition Cat that uses allOf to include all properties of Pet .

Cat:
  allOf:
    - $ref: '#/definitions/Pet'
    - type: object
      properties:
      # ...

The expectation is that when generating Java sources, we get

public class Cat extends Pet {

This works when using the Swagger Editor .

When using swagger-codegen-maven-plugin with no configOptions set, we get the following:

public class Cat {

Cat implements all of Pet 's properties itself, instead of extending it.

How do you tell the swagger-codegen-maven-plugin to use Java with inheritance (ie extends )? (We tried both spring and java as languages.)

Here's a sample swagger.yaml file:

swagger: '2.0'

info:
  version: 1.0.0
  title: simple inheritance

tags:
  - name: "pet"

paths:
  /cat:
    put:
      tags:
        - "pet"
      operationId: "updateCat"
      consumes:
        - "application/json"
      parameters:
        - in: "body"
          name: "body"
          required: true
          schema:
            $ref: "#/definitions/Cat"
      responses:
        200:
          description: Nada

definitions:
  Pet:
    type: "object"
    required:
      - "name"
    properties:
      name:
        type: "string"
        example: "doggie"
  Cat:
    allOf:
      - $ref: '#/definitions/Pet'
      - type: object
        properties:
          huntingSkill:
            type: string
        required:
          - huntingSkill

As pointed out on github by chiochuan , the workaround is to add

   discriminator: "type"

to the parent's definition to make the Java child classes extend it.

definitions:
  Pet:
    type: "object"
    discriminator: "type"
    required:
      - "name"
    properties:
      name:
        type: "string"
        example: "doggie"

It's a bit strange as the OpenAPI Specification Version 2.0 state that the discriminator Fixed Field must reference a property from the same schema, and that it must be a required property, both of which isn't the case - but it works, at least as of today. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM