Iam using openapi-generator-maven-plugin for generating code from my yml files.
<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.
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
:
<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
).
Find the file pojo.mustache
which is a template to generate a POJO files.
You need to understand some basic Mustache syntax at this point. Find sych a fragment:
[...]
{{^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.
Be aware that this is just a simple example how to proceed further. There are many corner cases eg enum
handling.
FUrther readings:
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.