Swagger Codegen使用现有类

Sni*_*192 5 swagger-codegen

我如何才能获得迅速的代码生成器以使用现有类而不是创建新类?这可能吗?例如,我想使用org.springframework.data.domain.Page而不是大胆地创建另一个页面类。

moo*_*isy 10

你可以使用--import-mappings,因为它是解释在这里

有时您不希望生成模型。在这种情况下,您只需指定一个导入映射即可告诉代码生成器不创建什么。这样做时,每个引用特定模型的位置都将引用您的类。

您可以在上调用它swagger-codegen-cli generate,其中包含的示例将是

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

尽管此处importMappings未包含在常规配置参数中,但是如果您在此处查看代码,则可以看到它是一个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> 
Run Code Online (Sandbox Code Playgroud)

但这是最近更改的,因此如果您使用的是旧版插件,则可能会有所不同。在那之前改变似乎是这样的:

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

根据该提交中的评论,也应该支持旧版本,但是我还没有尝试过任何版本,因此请让我知道它是否有效。

  • 您如何在 yml 文件中引用“Page”? (2认同)

Gmu*_*gra 5

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


Tan*_*vir 5

这里提到的答案都没有提到要添加到svagger yaml文件中的内容,以防万一有人感兴趣,这对我有用:

DisplayProperty:  
  type: object
  properties:
    name:
      type: string
    displayName:
      $ref: '#/components/schemas/Text'
    isRequired:
      type: boolean
      example: false
Text:
    type: object
Run Code Online (Sandbox Code Playgroud)

然后把它放在绒球里

<importMappings>
<importMapping>Text=com.--.--.--.--.Text</importMapping>
Run Code Online (Sandbox Code Playgroud)