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

SpringDoc自定义Schema命名策略适配HTTP客户端生成方案咨询

自定义SpringDoc Schema命名策略适配HTTP客户端生成

实现思路

SpringDoc自带的use-fqn选项会生成包含点(.)和美元符号($)的全限定类名,这类字符会导致HTTP客户端生成工具报错。我们可以通过实现SchemaNameGenerator接口,自定义Schema的命名规则,过滤掉非法字符,生成符合工具要求的类型名称。

具体步骤

1. 编写自定义Schema名称生成器

创建类实现org.springdoc.core.customizers.SchemaNameGenerator接口,在重命名逻辑中清理非法字符:

import org.springdoc.core.customizers.SchemaNameGenerator;
import java.lang.reflect.Type;
import java.util.regex.Pattern;

public class ClientFriendlySchemaNameGenerator implements SchemaNameGenerator {
    private static final Pattern ILLEGAL_CHARS = Pattern.compile("[\\.\\$]");

    @Override
    public String generate(Type type) {
        if (type instanceof Class<?>) {
            Class<?> clazz = (Class<?>) type;
            // 处理内部类(如Outer$Inner),直接移除$符号
            String rawName = clazz.getSimpleName();
            // 替换所有非法字符为空
            return ILLEGAL_CHARS.matcher(rawName).replaceAll("");
        }
        // 非Class类型的默认处理,可按需扩展
        return type.getTypeName().replaceAll("[\\.\\$]", "");
    }
}

2. 配置SpringDoc启用自定义生成器

在Spring Boot配置类中注册自定义Bean,覆盖默认的Schema命名生成逻辑:

import org.springdoc.core.customizers.SchemaNameGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringDocConfiguration {

    @Bean
    public SchemaNameGenerator schemaNameGenerator() {
        return new ClientFriendlySchemaNameGenerator();
    }
}

3. 关闭默认的全限定名选项

在配置文件中禁用use-fqn,避免默认逻辑干扰:

# application.properties
springdoc.swagger-ui.use-fqn=false

或者YAML格式:

# application.yml
springdoc:
  swagger-ui:
    use-fqn: false

进阶优化

如果需要处理更复杂的场景,比如泛型、同名类冲突,可以扩展generate方法:

  • 泛型处理:对ParameterizedType类型解析泛型参数,拼接成类似ListUser的名称
  • 同名类区分:保留部分包名前缀(替换非法字符),比如com.example.User转为ComExampleUser

验证

启动应用后访问/v3/api-docs,查看components.schemas下的键名,确认已替换掉非法字符,此时用该JSON生成HTTP客户端即可成功。

内容的提问来源于stack exchange,提问作者condiorno

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:31:20