How to generate constructors in swagger codegen?

巧了我就是萌 提交于 2019-11-30 19:14:26

If you really need a constructor with parameters you can do so by modifying the template file(s) that end with .moustache.

"enable/use/modify" templates

I'm going to assume you're going to be editing an existing template and want a constructor for each model.

Here is a simple example of a constructor inside the model template file:

public {{classname}}( {{#vars}} {{datatype}} {{baseName}}{{^-last}},{{/-last}} {{#-last}}){
construct code here
}{{/-last}}{{/vars}}

note that this should go between the {{#model}} {{/model}} tags

for more information about the moustache templates refer to

https://mustache.github.io/mustache.5.html

List of template variables

template examples for the codegen

I would first like to thank @Viktor Baert for his answer. While the answer provided direction it didn't provide enough to solve it. Note a change and an addition to the answer above.

The change is from {{datatype}} to {{{datatypeWithEnum}}} in the the constructor signature. This change will support any properties that use generics e.g List.

The second is the inclusion of the assignment of the parameters to the local variables.

When these changes are applied to pojo.mustache either directly or overriding the result is the generation of a usable constructor. This works with both the swagger and openapi generators.

public {{classname}}( {{#vars}} {{{datatypeWithEnum}}} {{baseName}}{{^-last}},{{/-last}} {{#-last}}){
  {{#vars}}
  this.{{baseName}} = {{baseName}};
  {{/vars}}
}{{/-last}}{{/vars}}

Reference:add constructors to code generated by openapi codegen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!