SpringCloud + React19 集成Scalar的API文档

你好呀,我的老朋友!我是老寇,跟我一起学习集成Scalr API文档

众所周知,Knife4j是一个集Swagger2 和 OpenAPI3 为一体的增强解决方案,但是社区不太活跃,再加上SpringBoot4 发版,迫切需要一个集成 OpenAPI 3.0 和 OpenAPI 3.1 规范的增强解决方案,所以才集成Scalar

React集成Scalar

React集成Scalar文档地址

安装依赖
shell 复制代码
pnpm install @scalar/api-reference-react
配置详情
配置项 类型 是否必填 说明 示例
sources Array 是 OpenAPI 文档源列表,一个配置可以配置多个 API 文档。 [{ title: "认证授权", url: "/api/v3/api-docs" }]
sources.title String 是 API 文档名称,在 Scalar 左侧导航中显示。 "认证授权"
sources.url String 是 OpenAPI(Swagger)JSON 文档地址。 "/api-proxy/auth/api/v3/api-docs"
sources.default Boolean 否 是否默认选中该文档。 true
proxyUrl String 否 Scalar 的代理地址,用于 Try It、鉴权等请求代理。 "/api-proxy/auth/scalar"
expandAllResponses Boolean 否 是否默认展开所有 Response。 true
hideClientButton Boolean 否 是否隐藏 Generate Client(生成客户端)按钮。 true
orderRequiredPropertiesFirst Boolean 否 Model 属性中,是否将必填字段排在前面。 true
expandAllModelSections Boolean 否 是否默认展开所有 Model 定义。 false
具体代码

apiDoc.tsx

javascript 复制代码
import {ApiReferenceReact} from '@scalar/api-reference-react'
import '@scalar/api-reference-react/style.css'
import { useIntl } from '@@/exports';

export default () => {
    const intl = useIntl();
    const t = (id: string, values?: Record<string, any>) =>
       intl.formatMessage({ id }, values);
    return (
       <ApiReferenceReact
          configuration={
          [
             {
                sources: [
                   {
                      title: '认证授权',
                      url: "/api-proxy/auth/api/v3/api-docs",
                      default: true,
                   }
                ],
                proxyUrl: "/api-proxy/auth/scalar",
                expandAllResponses: true,
                hideClientButton: true,
                orderRequiredPropertiesFirst: true,
                expandAllModelSections: false,
             },
             {
                sources: [
                   {
                      title: '后台管理',
                      url: "/api-proxy/admin/api/v3/api-docs",
                      default: true,
                   }
                ],
                proxyUrl: "/api-proxy/admin/scalar",
                expandAllResponses: true,
                hideClientButton: true,
                orderRequiredPropertiesFirst: true,
                expandAllModelSections: false,
             }
          ]
       }
       />
    );
};

Spring Cloud Gateway集成Scalar

由于代理地址为 /**/scalar 因此,需要在网关层将 /**/scalar 覆盖为 scalar_url

依赖
复制代码
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>
具体代码

ScalarGatewayFilterFactory

java 复制代码
@Slf4j
@Component
public class ScalarGatewayFilterFactory extends AbstractGatewayFilterFactory<ScalarGatewayFilterFactory.@NonNull Config>
       implements Ordered {

    public ScalarGatewayFilterFactory() {
       super(Config.class);
    }

    @Override
    public int getOrder() {
       return Ordered.LOWEST_PRECEDENCE - 2000;
    }

    @NonNull
    @Override
    public GatewayFilter apply(Config config) {
       return (exchange, chain) -> {
          ServerHttpRequest request = exchange.getRequest();
          // 获取uri
          String requestURL = ReactiveRequestUtils.getRequestURL(request);
          // scalar重写地址
          if (ReactiveRequestUtils.pathMatcher("/**/scalar", requestURL)) {
             String scalarUrl = ReactiveRequestUtils.getParamValue(request, "scalar_url");
             URI uri = URI.create(scalarUrl);
             return chain
                .filter(exchange.mutate().request(request.mutate().uri(uri).path(uri.getPath()).build()).build());
          }
          return chain.filter(exchange);
       };
    }

    public static class Config {

    }

}

application.yml

yaml 复制代码
spring:
  cloud:
    gateway:
      server:
        webflux:
          enabled: true
          routes:
            - id: laokou-auth-scalar
              uri: lb://laokou-auth
              predicates:
                - Path=/api-gateway/auth/scalar
              filters:
                - name: Scalar
            - id: laokou-admin-scalar
              uri: lb://laokou-admin
              predicates:
                - Path=/api-gateway/admin/scalar
              filters:
                - name: Scalar

SpringBoot集成Scalar(以laokou-auth为例)

安装依赖
xml 复制代码
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-scalar</artifactId>
</dependency>
具体代码

OpenApiDocConfig

java 复制代码
@Configuration
public class OpenApiDocConfig {

    @Bean
    OpenAPI openApi() {
       return new OpenAPI()
          .info(new Info().title("API文档")
             .description("API文档")
             .version("1.0.0")
             .contact(new Contact().name("laokou").url("https://github.com/KouShenhai").email("2413176044@qq.com"))
             .license(new License().name("Apache 2.0").url("https://www.apache.org/licenses/LICENSE-2.0.html")))
          .externalDocs(new ExternalDocumentation().description("老寇IoT云平台").url("https://github.com/KouShenhai"))
          .addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION))
          .components(new Components().addSecuritySchemes(HttpHeaders.AUTHORIZATION,
                new SecurityScheme().name(HttpHeaders.AUTHORIZATION)
                   .type(SecurityScheme.Type.OAUTH2)
                   .in(SecurityScheme.In.HEADER)
                   .scheme("Bearer")
                   .bearerFormat("JWT")));

    }

}

application.yml

yaml 复制代码
scalar:
  enabled: true
springdoc:
  swagger-ui:
    enabled: false
  api-docs:
    enabled: true
    path: /v3/api-docs
    version: openapi_3_1

我是老寇,我们下次再见啦!

相关推荐
陈随易8 分钟前
Node.js 2026上半年都有哪些性能提升?
前端·后端·程序员
hhcgchpspk20 分钟前
flask服务端页面预防被爬措施
后端·python·flask·网络爬虫·防爬
vipxieliang25 分钟前
Python collections:高效容器与实战案例
后端·python
驭渊的小故事38 分钟前
Spring AOP 核心概念与通知类型详解
java·后端·spring
vipxieliang39 分钟前
ValidX vs 手写验证代码:开发效率对比实测
java·spring boot·后端
vipxieliang1 小时前
Go GC 性能优化实践:从 GOGC、GOMEMLIMIT 到分配优化
后端·go
海豚调度1 小时前
Apache DolphinScheduler 2026 年 10 月社区贡献总结报告
后端
vipxieliang1 小时前
ThinkORM 3.0 入门:强类型模型定义与查询构造器
后端·php·thinkphp
vipxieliang1 小时前
虚拟线程与 GraalVM:Spring Boot 3.x 云原生性能跃迁
java·spring boot·后端
Rain的Java大神之路1 小时前
面试官最烦的答案:“我用 Redis + Token”!接口幂等 8 种方案 + 四层防御,把重复扣款工单干到 0
java·后端·面试