使用OpenAPITools 7.1生成继承测试类时openapiFields缺失子类字段
问题
使用org.openapitools 7.1版本生成带有继承关系的Java类时,子类的openapiFields静态字段仅包含父类的字段(如dataId、dataTypeId、type),子类自身的字段(如textValue)未被加入该集合,导致验证逻辑出错。
OpenAPI YAML片段
DataText: type: object required: - textValue properties: textValue: type: string allOf: - $ref: '#/components/schemas/ItemData' ItemData: type: object properties: dataId: type: integer description: data id dataTypeId: type: integer description: data type id type: type: string description: Discriminator property for ItemData. discriminator: propertyName: type mapping: DataText: '#/components/schemas/DataText'
生成的Java类片段
public class DataText extends ItemData { public static final String SERIALIZED_NAME_TEXT_VALUE = "textValue"; @SerializedName(SERIALIZED_NAME_TEXT_VALUE) private String textValue; ... static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet<String>(); openapiFields.add("dataId"); openapiFields.add("dataTypeId"); openapiFields.add("type"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet<String>(); openapiRequiredFields.add("textValue"); } }
解决方案
1. 修正OpenAPI YAML的结构写法
将子类自身的属性定义嵌套到allOf数组中作为第二个元素,这是OpenAPI规范中更标准的继承写法,能让生成器正确识别并合并父子类的字段:
DataText: allOf: - $ref: '#/components/schemas/ItemData' - type: object required: - textValue properties: textValue: type: string ItemData: type: object properties: dataId: type: integer description: data id dataTypeId: type: integer description: data type id type: type: string description: Discriminator property for ItemData. discriminator: propertyName: type mapping: DataText: '#/components/schemas/DataText'
2. 升级OpenAPI Generator版本
7.1版本存在子类字段未被加入openapiFields的已知问题,升级到7.2及以上版本后,该bug已被官方修复,无需修改YAML即可正常生成包含所有字段的openapiFields集合。
3. 自定义生成模板(进阶方案)
如果无法修改YAML或升级版本,可以自定义Java模型的生成模板:
- 找到OpenAPI Generator默认的
model.mustache模板文件 - 修改
openapiFields的生成逻辑,在遍历父类字段的同时,加入当前类自身的所有属性字段 - 在maven插件配置中指定自定义模板的路径:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>7.1.0</version> <configuration> <templateDirectory>${project.basedir}/src/main/resources/templates</templateDirectory> <!-- 其他配置 --> </configuration> </plugin>
内容的提问来源于stack exchange,提问作者Sergey
相关产品推荐
相关产品推荐

