用途:为 Spring Boot 项目搭建 GraphQL 服务端,基于 Spring for GraphQL,覆盖从 schema、解析器到安全与测试的常见环节。属项目脚手架类技能,触发词包括 apigen-graphql、@QueryMapping、@MutationMapping、DataLoader。
主要能力:
- 配置:可开启 GraphiQL(path /graphiql),schema 位置 classpath:graphql/,WebSocket 路径 /graphql;提供 apigen.graphql 下的 enabled、max-depth、max-complexity、introspection-enabled 等配置项。
- Schema 定义:示例含 Query、Mutation、Subscription,以及 User、Post、UserConnection/Edge、PageInfo、输入类型与 DateTime 标量。
- 解析器:用 @Controller 配合 @QueryMapping、@MutationMapping、@SubscriptionMapping、@SchemaMapping 编写查询、变更、订阅及嵌套字段解析。
- DataLoader:通过 BatchLoaderRegistry 注册批量加载器(如 usersById、postsByAuthorId),在解析器用 DataLoader 加载,缓解 N+1。
- 自定义标量:RuntimeWiringConfigurer 注册 ExtendedScalars.DateTime、UUID、JSON。
- 异常处理:@ControllerAdvice 配合 @GraphQlExceptionHandler 返回 GraphQLError,含错误类型与字段级校验信息。
- 安全限制:MaxQueryDepthInstrumentation 与 MaxQueryComplexityInstrumentation 限制查询深度和复杂度;用 @PreAuthorize 做方法级与字段级授权。
- 测试:@GraphQlTest 配合 GraphQlTester、@MockBean 进行查询与变更测试。
使用方式:按资料示例配置 application 配置、在 src/main/resources/graphql/schema.graphqls 定义 schema、编写各 @Controller 解析器,并注册 DataLoader、标量、异常处理器与 Instrumentation。
适用场景:Spring Boot 中需要 GraphQL API(含订阅与批量加载)的项目起步。
限制:资料未提供依赖坐标、构建命令、版本要求、许可证与部署步骤;具体能力以实际框架版本为准。