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

多Servlet端点Swagger文档路径映射错误问题求助

解决多JAX-RS端点Swagger文档路径错误问题

问题根源

你当前的Swagger配置是独立的ResourceConfig,它自身的@ApplicationPath("/swagger")会覆盖原有端点的路径前缀,导致生成的API路径变成/swagger/path1、/swagger/path2;同时因为未关联原有端点的配置逻辑,还会出现仅扫描到部分资源的情况。

解决方案

方案一:在每个端点应用中单独配置Swagger

直接在现有的Endpoint1和Endpoint2中注册Swagger组件,并指定对应端点的contextPath,确保Swagger继承当前应用的路径前缀:

修改Endpoint1:

@ApplicationPath("/endpoint_1")
public class Endpoint1 extends ResourceConfig {
    public Endpoint1() {
        register(SomeObject1.class);
        
        // 配置当前端点的Swagger参数
        SwaggerConfiguration swaggerConfig = new SwaggerConfiguration()
                .openAPI(new OpenAPI())
                .prettyPrint(true)
                .resourcePackages(Collections.singleton("你的资源类所在包名")) // 替换为实际包路径
                .contextPath("/endpoint_1"); // 匹配当前应用的路径前缀
        
        // 注册Swagger资源
        register(new OpenApiResource().setOpenApiConfiguration(swaggerConfig));
    }
}

修改Endpoint2:

@ApplicationPath("/endpoint_2")
public class Endpoint2 extends ResourceConfig {
    public Endpoint2() {
        register(SomeObject2.class);
        
        SwaggerConfiguration swaggerConfig = new SwaggerConfiguration()
                .openAPI(new OpenAPI())
                .prettyPrint(true)
                .resourcePackages(Collections.singleton("你的资源类所在包名"))
                .contextPath("/endpoint_2");
        
        register(new OpenApiResource().setOpenApiConfiguration(swaggerConfig));
    }
}

访问方式:

  • Endpoint1的API文档:/endpoint_1/openapi.json(或/endpoint_1/swagger.json,取决于Swagger版本)
  • Endpoint2的API文档:/endpoint_2/openapi.json

方案二:统一配置Swagger并关联所有端点

如果需要一个统一的文档入口,可创建全局Swagger配置,扫描所有端点应用并映射它们的路径前缀:

@ApplicationPath("/swagger")
public class OpenApiConfig extends ResourceConfig {
    public OpenApiConfig() {
        // 指定所有资源类的扫描包
        String resourcePackage = "你的资源类所在包名";
        
        SwaggerConfiguration oasConfig = new SwaggerConfiguration()
                .openAPI(new OpenAPI())
                .prettyPrint(true)
                .resourcePackages(Collections.singleton(resourcePackage))
                .contextPaths(Arrays.asList("/endpoint_1", "/endpoint_2")); // 声明所有端点的路径前缀
        
        OpenApiResource swaggerResource = new OpenApiResource();
        swaggerResource.setOpenApiConfiguration(oasConfig);
        
        // 注册Swagger资源及所有端点应用
        register(swaggerResource);
        register(Endpoint1.class);
        register(Endpoint2.class);
    }
}

效果:访问/swagger/openapi.json时,生成的API路径会自动关联对应端点的前缀,即endpoint_1/path1、endpoint_2/path2。

注意事项

  • 确保swagger-jaxrs2(或对应OpenAPI依赖)版本支持多上下文路径配置,建议使用2.0及以上版本。
  • resourcePackages必须准确指向包含SomeObject1、SomeObject2的包,否则Swagger无法扫描到资源类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:15:34