Create model classes with openapi generator which implements external interface
Asked Answered
L

2

7

I am using openapi-generator to generate java classes.

I want the model classes to implement an external interface which has not been generated by openapi-generator.

Is there something that can be defined within the model yaml or a property that can be passed to the openapi-generator-maven-plugin which allows for this behaviour?

Example of required behaviour:

package com.example.model;

/**
 * ExampleModel
 */
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen")
public class ExampleModel implements com.example.CustomInterface {
  @JsonProperty("property1")
  private String property1;

  @JsonProperty("property2")
  private String property2;
Lacerated answered 22/9, 2020 at 8:30 Comment(0)
L
7

Since openapi-generator-maven-plugin version 6.0.0 there is a better way: x-implements

Simply modify the schema-definition in your api.yml and the generated java-classes will implement the specified interfaces

openapi: 3.0.0
components:
  schemas:
    MyObject:
      type: object
      description: object that will implement interface
      x-implements: ['com.example.Interface']
      properties:
        data:
          description: some data
          type: object

(The feature existed in earlier versions but was bugged, this has been fixed: https://github.com/OpenAPITools/openapi-generator/issues/11636)

NOTE: you must use the fully-qualified interface name, eg java.io.Serializable instead of just Serializable

Lundell answered 22/6, 2022 at 12:56 Comment(0)
E
3

In case you want to modify all of the classes in the same way I would opt for changing the template. In your case that is most probably this file: pojo.mustache

Just copy it over to your src/main/resources/ folder (maybe in a subfolder named custom) and adapt it according to your needs.

Then you need to adapt your pom.xml, too:

<configuration>

    <!-- The following line is crucial: -->
    <templateDirectory>${project.basedir}/src/main/resources/custom</templateDirectory>

    <!-- Your other config goes here: -->
    <inputSpec>${project.basedir}/src/main/resources/api.yaml</inputSpec>
    <generatorName>java</generatorName>
    <configOptions>
        <sourceFolder>src/gen/java/main</sourceFolder>
    </configOptions>
</configuration>

Also have a look at this templating documentation for more information on the subject.

Enclasp answered 2/10, 2020 at 6:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.