You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringDoc中如何将@ArraySchema配置提取为自定义注解实现复用

实现方案

Swagger V3(SpringDoc)原生支持将官方注解作为元注解标注在自定义注解上,你可以通过以下步骤抽离复用配置:

步骤1:创建自定义复合注解

import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Schema;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// 限定注解只能用在类字段上
@Target(ElementType.FIELD)
// 运行时保留注解信息供Swagger读取
@Retention(RetentionPolicy.RUNTIME)
// 直接把原有的ArraySchema配置作为元注解放在此处
@ArraySchema(
    schema = @Schema(type = "string"),
    arraySchema = @Schema(
        // SpEL表达式引用当前自定义注解的属性值,支持动态覆盖
        example = "#{currentAnnotation.example()}",
        description = "#{currentAnnotation.description()}"
    )
)
public @interface CurrencyCodesList {
    // 配置默认值,使用时不传就用默认配置
    String example() default "[\"USD\",\"CAD\"]";
    String description() default "Currencies supported by store according to ISO_4217.";
}

步骤2:在DTO中直接使用

替换原有字段上的全部@ArraySchema相关配置即可,效果完全一致:

import javax.money.CurrencyUnit;
import java.util.List;

public class YourBusinessDTO {
    // 直接使用抽离后的注解
    @CurrencyCodesList
    private List<CurrencyUnit> currencies;

    // 也可以按需覆盖默认配置
    // @CurrencyCodesList(example = "[\"CNY\",\"EUR\"]", description = "当前商户支持的结算货币列表")
    // private List<CurrencyUnit> supportedCurrencies;

    // 其他字段、getter、setter省略
}

内容的提问来源于stack exchange,提问作者Антон Ткаченко

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 21:24:03