如何让swagger codegen使用现有的类而不是创建新的类?这可能吗?例如,我想使用org.springframework.data.domain.Page
而不是swagger创建另一个页面类。
你可以使用--import-mappings
,因为它解释here:
有时您不希望生成模型。在这种情况下,您可以简单地指定导入映射以告知codegen不要创建的内容。执行此操作时,引用特定模型的每个位置都将引用您的类。
你在swagger-codegen-cli generate
上调用它,你将包括它的例子
--import-mappings Page=org.springframework.data.domain.Page
虽然importMappings
没有被包括在一般配置参数here中,如果你看一下代码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>
根据该提交中的评论,旧版本也应该受到支持,但我还没有尝试过这个,所以让我知道它是否有效。
这里提到的答案都没有谈到要添加到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>
如果你有很长的映射列表,并不总是可以使用--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"
}
}