简体   繁体   English

openapi 生成 - 初始化对象

[英]openapi generation - initialize objects

Iam using openapi-generator-maven-plugin for generating code from my yml files.我使用 openapi-generator-maven-plugin 从我的 yml 文件生成代码。

<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>3.3.4</version>

When generating objects from the yml the generated code always generate objects and initilize them with null.当从 yml 生成对象时,生成的代码总是生成对象并用 null 初始化它们。

For example:例如:

public class Foo   {
  @JsonProperty("bar")
  private Bar bar = null;
}

Is there a way that the object is initialized with the object itself like:有没有办法用对象本身初始化对象,例如:

public class Foo   {
  @JsonProperty("bar")
  private Bar bar = new Bar();
}

Some snippets and links which can help You.一些可以帮助您的片段和链接。

Plugin config in pom.xml : pom.xml插件配置:

<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>4.2.2</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/docs/openapi/api.yml</inputSpec>
                <generatorName>java</generatorName>
                <templateDirectory>docs/openapi/template</templateDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

Copy default templates eg from Java module of OpenAPI generator and put all mustache files inside some directory in Your project - check plugin configuration (in my case it is docs/openapi/template ).OpenAPI 生成器的 Java 模块复制默认模板,并将所有 mustache 文件放在您的项目中的某个目录中 - 检查插件配置(在我的情况下是docs/openapi/template )。

Find the file pojo.mustache which is a template to generate a POJO files.找到文件pojo.mustache ,它是生成 POJO 文件的模板。

You need to understand some basic Mustache syntax at this point.此时您需要了解一些基本的 Mustache 语法。 Find sych a fragment:查找 sych 片段:

[...]
{{^isContainer}}
  private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}};
{{/isContainer}}
[...]

Change to whatever You want, eg:更改为您想要的任何内容,例如:

[...]
{{^isContainer}}
private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{^defaultValue}}{{^isPrimitiveType}} = new {{datatypeWithEnum}}(){{/isPrimitiveType}}{{/defaultValue}};
{{/isContainer}}
[...]

This template snippet will generate new TypeYouWantToUse() parts for every non primitive datatype.此模板片段将为每个非原始数据类型生成new TypeYouWantToUse()部分。

Be aware that this is just a simple example how to proceed further.请注意,这只是如何进一步进行的一个简单示例。 There are many corner cases eg enum handling.有许多极端情况,例如enum处理。

FUrther readings:进一步阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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