Swagger Codegen 使用现有 class

Swagger Codegen use existing class

如何让 swagger codegen 使用现有的 class 而不是创建新的 class?这可能吗?例如,我想使用 org.springframework.data.domain.Page 而不是大摇大摆地创建另一个页面 class.

您可以使用 --import-mappings,正如所解释的 here:

Sometimes you don't want a model generated. In this case, you can simply specify an import mapping to tell the codegen what not to create. When doing this, every location that references a specific model will refer back to your classes.

你在 swagger-codegen-cli generate 上调用它,你包含的例子是

--import-mappings Page=org.springframework.data.domain.Page

虽然 importMappings 没有包含在通用配置参数中 here if you look at the code here 你可以看到它是一个 List<String>。 我没有将它与 Maven 插件一起使用,但查看文档和代码我猜这应该可以工作:

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.2-SNAPSHOT</version>
    <executions>
        <execution>
            ...
            <configuration>
                ...
                <importMappings>
                   <importMapping>Page=org.springframework.data.domain.Page</importMapping>
                </importMappings>
            </configuration>
        </execution>
    </executions>
</plugin> 

但这是 recently changed,所以如果您使用的是旧版本的插件,它可能会有所不同。在那改变之前它似乎是这样的:

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.2-SNAPSHOT</version>
    <executions>
        <execution>
            ...
            <configuration>
                ...
                <configOptions>
                   <import-mappings>Page=org.springframework.data.domain.Page;Some=org.example.Some</import-mappings>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

根据该提交中的评论,旧版本也应该受支持,但我还没有尝试过任何一个,所以如果它有效,请告诉我。

如果您的映射列表很长,则不一定总是可以使用 --import-mappings。 (至少在 Windows 的情况下,它在命令提示符中对字符串有大小限制。) 这就是为什么更好的方法:使用带有 swagger 配置文件的映射。 (并且此选项没有完整记录。)

像那样:

java -jar swagger-codegen-cli-2.3.1.jar generate -i myspec.yaml -l java -c myconfig.json

myconfig.json:

{
  "hideGenerationTimestamp": true,
  "dateLibrary": "java8",
  "useRuntimeException": true,
  "modelPackage": "org.my.package.model",
  "apiPackage": "org.my.package.api",
  "importMappings": {
    "Page": "org.springframework.data.domain.Page",
    "MySuperType": "org.my.SuperType"
  }
}
这里提到的

None个回答都讲了要往swagger yaml文件中添加什么, 如果有人感兴趣,这对我有用:

DisplayProperty:  
  type: object
  properties:
    name:
      type: string
    displayName:
      $ref: '#/components/schemas/Text'
    isRequired:
      type: boolean
      example: false
Text:
    type: object

然后在 pom 中加入这个

<importMappings>
<importMapping>Text=com.--.--.--.--.Text</importMapping>