使用实现外部接口的 openapi 生成器创建模型类

Sia*_*ian 5 java openapi openapi-generator

我正在使用 openapi-generator 生成 java 类。

我希望模型类实现一个尚未由 openapi-generator 生成的外部接口。

是否可以在模型 yaml 中定义某些内容,或者可以传递给 openapi-generator-maven-plugin 的属性来实现此行为?

所需行为的示例:

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;
Run Code Online (Sandbox Code Playgroud)

jul*_*ine 6

自 openapi-generator-maven-plugin 版本 6.0.0 以来,有一个更好的方法:x-implements

只需修改 api.yml 中的模式定义,生成的 java 类将实现指定的接口

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
Run Code Online (Sandbox Code Playgroud)

(该功能在早期版本中已存在,但已被修复,现已修复:https ://github.com/OpenAPITools/openapi-generator/issues/11636 )

注意:您必须使用完全限定的接口名称,例如 java.io.Serializing 而不仅仅是 Serialized


phi*_*ous 3

如果您想以相同的方式修改所有类,我会选择更改模板。在您的情况下,很可能是这个文件:pojo.mustache

只需将其复制到您的src/main/resources/文件夹(可能在名为 custom 的子文件夹中)并根据您的需要进行调整。

然后你也需要调整你的pom.xml

<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>
Run Code Online (Sandbox Code Playgroud)

另请参阅此模板文档以获取有关该主题的更多信息。