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

发布时间:2021-11-15 15:52:17 作者:柒染
来源:亿速云 阅读:373

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

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

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

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

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

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

 @Autowired
DocumentationCache documentationCache;

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

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

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

  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<String, ApiListing> 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<Tag> 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<Tag> addApi(Multimap<String, ApiListing> apiListings,
                            String basePath,
                            String beanName,
                            String methodName) {
    // 获取名称, 去除后缀
    String optGroup = getName(beanName);
    String apiId = optGroup + "_" + methodName; // 全局唯一
    String optId = methodName;

    // 采用 apiID,检测是否唯一,后续加到同一个tag下
    Collection<ApiListing> apis = apiListings.get(apiId);
    if(apis == null) {
        // 后面只是用 apis 的 size 获取长度
        apis = new HashSet<>();
    }

    ArrayList<ApiDescription> apis1 = new ArrayList<>();
    ArrayList<Operation> 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<Tag> tags = new HashSet<>();

    // description 是生成 API JS 的文件名
    // optGroup 是生成的函数名
    Tag tag = new Tag(optGroup, optGroup + "Controller");
    tags.add(tag);
    
    //暂时先不要参数
    ArrayList<Parameter> 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注册的示例分析

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

推荐阅读:
  1. 如何配置Swagger?
  2. django-rest-swagger如何优化使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

swagger

上一篇:怎么使用tcpdump

下一篇:Redis 有序集合对象底层实现是怎样的

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》