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

如何修改SpringFox Docket生成的Swagger JSON中泛型括号显示

解决SpringFox生成Swagger时泛型类双尖括号<<>>显示为方括号[]的问题

要修正SpringFox生成Swagger JSON时泛型类的格式问题,你需要自定义类型名称解析逻辑,替换默认的双尖括号输出为方括号。具体步骤如下:

1. 自定义类型名称提供者类

创建一个继承自DefaultTypeNameProvider的类,重写泛型类型的名称生成逻辑:

import springfox.documentation.schema.DefaultTypeNameProvider;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.stream.Collectors;

public class CustomTypeNameProvider extends DefaultTypeNameProvider {
    @Override
    public String nameFor(Type type) {
        // 处理参数化泛型类型
        if (type instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) type;
            // 获取原始类型名称
            String rawTypeName = super.nameFor(paramType.getRawType());
            // 处理泛型参数,递归解析嵌套泛型
            String typeArgs = Arrays.stream(paramType.getActualTypeArguments())
                    .map(this::nameFor)
                    .collect(Collectors.joining(", "));
            // 拼接成 [参数] 的格式
            return rawTypeName + "[" + typeArgs + "]";
        }
        // 非泛型类型使用默认逻辑
        return super.nameFor(type);
    }
}

2. 在Swagger配置中注册自定义提供者

修改你的Docket配置类,将自定义的TypeNameProvider注入到Swagger配置中:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.schema.TypeNameProvider;

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("你的接口所在包路径"))
                .paths(PathSelectors.any())
                .build()
                // 绑定自定义类型名称提供者
                .typeNameProvider(new CustomTypeNameProvider());
    }

    // 注册Bean确保全局生效(可选,视SpringFox版本调整)
    @Bean
    public TypeNameProvider typeNameProvider() {
        return new CustomTypeNameProvider();
    }
}

3. 验证结果

重启应用后,访问Swagger UI或直接查看生成的Swagger JSON文件,泛型类Human<Carl>会被正确显示为Human[Carl]。

补充说明

  • 如果你使用SpringFox 3.x版本,配置逻辑基本一致,只需确保typeNameProvider被正确关联到Docket实例。
  • 若存在嵌套泛型(如Human<Response<Carl>>),上述代码会自动处理为Human[Response[Carl]],无需额外修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 01:50:03