基于.graphqls文件离线生成GraphQL JSON Schema的JVM工具咨询(使用com.graphql-java-kickstart与Spring Boot)
无需启动Spring Boot服务器生成GraphQL JSON Schema的JVM方案
既然你用的是com.graphql-java-kickstart和Spring Boot,而且想要基于本地.graphqls文件生成和/graphql/schema.json一致的结果(本质是GraphQL自省查询的JSON输出),这里有几个纯JVM的方案,完全不需要启动服务器:
方案1:直接用graphql-java核心API手动生成
graphql-java本身就支持解析SDL文件并执行自省查询,这是最灵活的方式,适合嵌入到测试或脚本中:
步骤和代码示例
- 确保你的项目依赖了
graphql-java和Jackson(用来序列化JSON):
<dependency> <groupId>com.graphql-java</groupId> <artifactId>graphql-java</artifactId> <version>21.3</version> <!-- 使用对应版本 --> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency>
- 编写Java代码读取SDL、生成Schema并输出JSON:
import graphql.ExecutionResult; import graphql.GraphQL; import graphql.schema.GraphQLSchema; import graphql.schema.idl.RuntimeWiring; import graphql.schema.idl.SchemaGenerator; import graphql.schema.idl.SchemaParser; import graphql.schema.idl.TypeDefinitionRegistry; import com.fasterxml.jackson.databind.ObjectMapper; import java.nio.file.Files; import java.nio.file.Paths; public class LocalSchemaToJson { public static void main(String[] args) throws Exception { // 读取本地的SDL文件(单个) String sdlContent = Files.readString(Paths.get("src/main/resources/schema.graphqls")); // 解析SDL得到类型注册表 SchemaParser parser = new SchemaParser(); TypeDefinitionRegistry typeRegistry = parser.parse(sdlContent); // 配置RuntimeWiring:如果你的Schema有自定义标量、DataFetcher等,需要在这里注册 // 纯结构的SDL可以直接用empty RuntimeWiring wiring = RuntimeWiring.newRuntimeWiring().build(); // 生成可执行的GraphQL Schema SchemaGenerator generator = new SchemaGenerator(); GraphQLSchema schema = generator.makeExecutableSchema(typeRegistry, wiring); // 执行标准的GraphQL自省查询 String introspectionQuery = graphql.introspection.IntrospectionQuery.INTROSPECTION_QUERY; GraphQL graphQL = GraphQL.newGraphQL(schema).build(); ExecutionResult result = graphQL.execute(introspectionQuery); // 将结果序列化为格式化的JSON ObjectMapper objectMapper = new ObjectMapper(); String jsonSchema = objectMapper.writerWithDefaultPrettyPrinter() .writeValueAsString(result.getData()); // 输出到控制台或写入文件 System.out.println(jsonSchema); Files.writeString(Paths.get("schema.json"), jsonSchema); } }
方案2:用graphql-java-kickstart的工具类
如果你想和项目中已用的graphql-java-kickstart生态保持一致,可以用他们的graphql-java-tools库来解析SDL,它对多文件合并、自定义标量的支持更贴合Spring Boot场景:
代码示例
- 添加依赖:
<dependency> <groupId>com.graphql-java-kickstart</groupId> <artifactId>graphql-java-tools</artifactId> <version>12.0.0</version> <!-- 匹配你的kickstart版本 --> </dependency>
- 解析并生成JSON:
import com.graphql-java-kickstart.tools.SchemaParser; import graphql.ExecutionResult; import graphql.GraphQL; import graphql.schema.GraphQLSchema; import com.fasterxml.jackson.databind.ObjectMapper; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class KickstartSchemaToJson { public static void main(String[] args) throws Exception { // 读取多个SDL文件(支持批量处理) List<String> sdlPaths = List.of( "src/main/resources/user.graphqls", "src/main/resources/order.graphqls" ); List<String> sdlContents = sdlPaths.stream() .map(path -> { try { return Files.readString(Paths.get(path)); } catch (Exception e) { throw new RuntimeException("Failed to read SDL file: " + path, e); } }) .toList(); // 用kickstart的SchemaParser生成Schema GraphQLSchema schema = SchemaParser.newParser() .sdlStrings(sdlContents) // 如果有自定义标量,在这里注册:.scalar(CustomScalar.class) .build() .makeExecutableSchema(); // 执行自省查询并序列化JSON String introspectionQuery = graphql.introspection.IntrospectionQuery.INTROSPECTION_QUERY; ExecutionResult result = GraphQL.newGraphQL(schema).build().execute(introspectionQuery); ObjectMapper objectMapper = new ObjectMapper(); String jsonSchema = objectMapper.writerWithDefaultPrettyPrinter() .writeValueAsString(result.getData()); Files.writeString(Paths.get("schema.json"), jsonSchema); } }
方案3:用Maven插件自动生成(推荐用于构建流程)
如果想在Maven构建阶段自动生成schema.json,不需要手动写代码,可以用graphql-java-kickstart的Maven插件:
pom.xml配置
<build> <plugins> <plugin> <groupId>com.graphql-java-kickstart</groupId> <artifactId>graphql-maven-plugin</artifactId> <version>12.0.0</version> <executions> <execution> <goals> <goal>generate-schema</goal> </goals> <configuration> <!-- 匹配你的SDL文件位置 --> <schemaLocationPattern>src/main/resources/**/*.graphqls</schemaLocationPattern> <!-- 输出文件路径 --> <outputFile>target/generated-resources/schema.json</outputFile> <!-- 开启自省JSON生成 --> <generateIntrospectionJson>true</generateIntrospectionJson> <!-- 如果有自定义标量,在这里配置 --> <!-- <scalars> <scalar> <name>DateTime</name> <className>com.yourpackage.DateTimeScalar</className> </scalar> </scalars> --> </configuration> </execution> </executions> </plugin> </plugins> </build>
运行mvn generate-resources后,插件会自动解析所有匹配的SDL文件,生成和/graphql/schema.json完全一致的JSON文件。
注意事项
- 如果你的Schema包含自定义标量,必须在RuntimeWiring(代码方案)或插件配置中注册对应的标量实现,否则解析会失败。
- 自省查询返回的JSON就是
/graphql/schema.json的内容,因为Spring Boot的graphql端点本质上也是执行这个查询来返回结果的。
内容的提问来源于stack exchange,提问作者wIgor
相关产品推荐
相关产品推荐

