如何为swagger-codegen-maven-plugin 3.x生成类添加@JsonIgnoreProperties注解
解决Swagger Codegen 3.x生成类添加@JsonIgnoreProperties的问题
针对Swagger Codegen Maven插件3.0.36版本,你可以通过以下两种方式实现给生成的模型类添加@JsonIgnoreProperties(ignoreUnknown = true)注解:
1. 全局配置(推荐)
直接在插件的configOptions中添加ignoreUnknownProperties=true参数,生成的所有模型类会自动带上该注解。
在pom.xml中的插件配置示例:
<plugin> <groupId>io.swagger.codegen.v3</groupId> <artifactId>swagger-codegen-maven-plugin</artifactId> <version>3.0.36</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/api.yaml</inputSpec> <language>java</language> <configOptions> <!-- 开启全局忽略未知属性 --> <ignoreUnknownProperties>true</ignoreUnknownProperties> <!-- 其他自定义配置 --> <dateLibrary>java8</dateLibrary> <java8>true</java8> </configOptions> </configuration> </execution> </executions> </plugin>
执行mvn clean generate重新生成代码后,所有模型类会自动添加@JsonIgnoreProperties(ignoreUnknown = true)注解,无需手动修改。
2. 自定义模板(精细化控制)
如果需要仅给特定类添加注解,或者要修改注解的其他属性,可以自定义Mustache模板:
- 找到Swagger Codegen默认的Java模型模板
model.mustache - 在类定义上方的注解区域添加
@JsonIgnoreProperties(ignoreUnknown = true) - 在插件配置中通过
templateDirectory指定自定义模板目录:
<configuration> <!-- 其他配置 --> <templateDirectory>${project.basedir}/src/main/resources/swagger-templates</templateDirectory> </configuration>
内容的提问来源于stack exchange,提问作者srini
相关产品推荐
相关产品推荐

