如何在Swagger中仅显示PriceConfigDTO关联实体的ID字段而非完整属性树
解决方案
根本原因
默认Swagger/OpenAPI组件生成示例结构时,会直接通过反射扫描实体类的全量字段,不会默认读取Jackson的@JsonIgnore、@JsonIncludeProperties等注解配置,因此会展示所有关联实体的完整属性。
方案1:接口层单独定义轻量DTO(最推荐)
从架构层面解耦接口层和业务/持久层的实体,避免内部实体属性泄露到接口文档。
- 定义仅包含ID的通用关联对象DTO:
// 通用仅返回ID的DTO,可复用在所有关联对象场景 public class IdOnlyDTO { private String id; // 补充getter、setter方法 }
- 替换
PriceConfigDTO中的关联实体类型:
public class PriceConfigDTO { private Integer value; private String priceType; private List<String> taxesConfigIds; // 替换原来的ItemPricingConfig类型为IdOnlyDTO private IdOnlyDTO itemPricingConfig; // 替换原来的List<PriceConfigHistory>类型为List<IdOnlyDTO> private List<IdOnlyDTO> priceConfigHistory; // 补充你需要保留的其他字段、getter、setter方法 }
方案2:通过Swagger/OpenAPI注解强制指定示例结构
如果不想新增DTO,可以直接通过Swagger提供的注解覆盖默认的示例生成逻辑,不影响实际业务代码的实体定义。
如果你使用springdoc-openapi(OpenAPI 3.x版本):
import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Schema; public class PriceConfigDTO { private Integer value; private String priceType; private List<String> taxesConfigIds; // 指定关联字段仅展示ID结构 @Schema(implementation = IdOnlySchema.class) private ItemPricingConfig itemPricingConfig; @ArraySchema(schema = @Schema(implementation = IdOnlySchema.class)) private List<PriceConfigHistory> priceConfigHistory; // 内部定义仅用于Swagger示例生成的结构 static class IdOnlySchema { @Schema(example = "3fa85f64-5717-4562-b3fc-2c963f66afa6") private String id; } // 其他原有字段、getter、setter方法 }
如果你使用Springfox(Swagger 2.x版本):
直接在DTO类上标注全量示例:
import io.swagger.annotations.ApiModel; @ApiModel(example = "{" + " \"value\": 0,\n" + " \"priceType\": \"WHOLESALE\",\n" + " \"taxesConfigIds\": [\n" + " \"3fa85f64-5717-4562-b3fc-2c963f66afa6\"\n" + " ],\n" + " \"itemPricingConfig\": {\n" + " \"id\": \"itemprincingconfig_id\"\n" + " },\n" + " \"priceConfigHistory\": [\n" + " {\n" + " \"id\": \"3fa85f64-5717-4562-b3fc-2c963f66afa6\"\n" + " }\n" + " ]\n" + "}") public class PriceConfigDTO { // 原有字段、getter、setter方法 }
方案3:配置Swagger读取Jackson注解
如果希望Jackson的序列化规则同时对接口返回和Swagger示例生效,可修改Swagger配置,让其使用Jackson的序列化逻辑生成示例:
springdoc-openapi配置(application.yml):
springdoc: api-docs: # 关闭默认的反射扫描字段逻辑,使用Jackson规则生成schema resolve-schema-properties-using-reflection: false
Springfox配置:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import com.fasterxml.jackson.databind.ObjectMapper; @Configuration public class SwaggerConfig { @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) { return new MappingJackson2HttpMessageConverter(objectMapper); } }
内容的提问来源于stack exchange,提问作者leorosignoli
相关产品推荐
相关产品推荐

