千家信息网

Swagger扩展开发中任意架构实现Swagger Doc注册的示例分析

发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,这篇文章给大家介绍Swagger扩展开发中任意架构实现Swagger Doc注册的示例分析,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。缘起:公司08年以前的老项目,跟着迭代了一
千家信息网最后更新 2026年11月03日Swagger扩展开发中任意架构实现Swagger Doc注册的示例分析

这篇文章给大家介绍Swagger扩展开发中任意架构实现Swagger Doc注册的示例分析,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

缘起:公司08年以前的老项目,跟着迭代了一个版本,架构太老自己干着也受气。于是提议升级为SpringBoot 这种新的能好受一点。但是老接口太多,老接口是通过自定义实现的Servlet,按照扫描Bean 函数通过反射的方式调用。也不想把所有接口都转为新的,旧接口前端要 Swagger 没办法,硬着头皮上。

查了大量资料,都是 SpringBoot 集成 Swagger,重复、简单技术含量很低,没找到我想要的。

首先把项目一通整合,一通重构支持了 SpringBoot,通过SpringBoot 启动,并且集成了Swagger,新写的RESTAPI 都支持Swagger。现在需要扫描旧接口,生成Swagger。

  1. 实现一个Spring ApplicationListener,在Spring ApplicationContext 初始化完成后调用,用于生成旧接口的Swagger 扫描。

@Repositorypublic class SwaggerExtentionSupport implements ApplicationListener {    @Override    public void onApplicationEvent(ContextRefreshedEvent event) {        // Spring 框架加载完全后,扫描 bean,获取 servlet        initSwagger(event.getApplicationContext());    }}
  1. 注入 DocumentationCache

 @AutowiredDocumentationCache documentationCache;// Swagger 默认是 Default,就接口我们放到自定义的 group 下@Value("${swagger.group}")private String groupName;

通过 Debug,发现新实现的SpringBoot接口,构造的如下:

  1. 开始扫描接口

private void initSwagger(ApplicationContext context) {    Documentation documentation = documentationCache.documentationByGroup(groupName);    if(documentation == null) {        // 如果 groupName 指定的下没有,则挂载 default 上        documentation = documentationCache.documentationByGroup(Docket.DEFAULT_GROUP_NAME);    }    if (documentation != null) {        // 取得所有的 API 合集        Multimap apiListings = documentation.getApiListings();        Class[] clazzs = ... //Scan Classes        for (Class aClass : clazzs) {            log.info("add swagger bean {}", aClass.getSimpleName());            Method[] servletMethods = aClass.getDeclaredMethods();            for (Method servletMethod : servletMethods) {                String methodName = servletMethod.getName();                // 获得接口名称,必须符合是API接口,且方法是 public                if(validSwagger(methodName) && Modifier.isPublic(servletMethod.getModifiers())) {                    // 返回 tags                    Set tags = addApi(apiListings, documentation.getBasePath(), name, methodName);                    if(!tags.isEmpty()) {                        documentation.getTags().addAll(tags);                    }                }            }            log.info("swagger apis size: {}", apiListings.size());        }    }}
  1. 把扫描到合法的添加到Swagger

private Set addApi(Multimap apiListings,                            String basePath,                            String beanName,                            String methodName) {    // 获取名称, 去除后缀    String optGroup = getName(beanName);    String apiId = optGroup + "_" + methodName; // 全局唯一    String optId = methodName;    // 采用 apiID,检测是否唯一,后续加到同一个tag下    Collection apis = apiListings.get(apiId);    if(apis == null) {        // 后面只是用 apis 的 size 获取长度        apis = new HashSet<>();    }    ArrayList apis1 = new ArrayList<>();    ArrayList operations = new ArrayList<>();    ResponseMessage v200 = new ResponseMessageBuilder().code(200).message("OK").build();    ResponseMessage v401 = new ResponseMessageBuilder().code(401).message("Unauthorized").build();    ResponseMessage v403 = new ResponseMessageBuilder().code(403).message("Forbidden").build();    ResponseMessage v404 = new ResponseMessageBuilder().code(404).message("Not Found").build();    // tag,Swagger 首页展示的都是tag,tag下挂载的是接口    HashSet tags = new HashSet<>();    // description 是生成 API JS 的文件名    // optGroup 是生成的函数名    Tag tag = new Tag(optGroup, optGroup + "Controller");    tags.add(tag);        //暂时先不要参数    ArrayList parameters = new ArrayList<>();       // 注意 position,必须是不重复的值,数值 0-n    // Operation 只需要 tag name,他决定了该 api 在 Swagger 上挂载的tag    Operation operaGet = new Operation(                HttpMethod.GET,                "do exec " + optGroup + "." + methodName,                "",                new ModelRef("string"),                optId+"UsingGET",                0,                Sets.newHashSet(tag.getName()),                Sets.newHashSet(MediaType.ANY_TYPE.toString()),                Sets.newHashSet(MediaType.create("application", "json").toString()),                new HashSet<>(),                new ArrayList<>(),                parameters,                Sets.newHashSet(v200, v401, v403, v404),                "",                false,                new ArrayList<>()        );    operations.add(operaGet);    //operations.add(operaPost);    String url = "/" + beanName + "?invoke=" + methodName;    apis1.add(new ApiDescription(groupName,                url,                beanName+"." + methodName,                operations, false));    // 注意 position,必须是不重复的值,这里我用 apis.size()    ApiListing apiListing = new ApiListing(                API_VER,                basePath,                "/" + beanName,                new HashSet<>(),new HashSet<>(),"", new HashSet<>(), new ArrayList<>(),                apis1,                new HashMap<>(), beanName+"." + methodName, apis.size(), tags);    // 放到api列表中    apiListings.put(apiId, apiListing);    // 返回 tag,tag 会显示到 Swagger Content    return tags;}

生成 Swagger 效果如:

关于Swagger扩展开发中任意架构实现Swagger Doc注册的示例分析就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

0