GraphQL Java 项目教程
graphql-javaGraphQL Java implementation项目地址:https://gitcode.com/gh_mirrors/gr/graphql-java
1. 项目的目录结构及介绍
GraphQL Java 项目的目录结构如下:
graphql-java/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ ├── graphql/
│ │ │ │ ├── execution/
│ │ │ │ ├── language/
│ │ │ │ ├── schema/
│ │ │ │ ├── validation/
│ │ │ │ └── ...
│ │ └── resources/
│ └── test/
│ ├── java/
│ │ ├── graphql/
│ │ │ ├── execution/
│ │ │ ├── language/
│ │ │ ├── schema/
│ │ │ ├── validation/
│ │ │ └── ...
│ └── resources/
├── pom.xml
├── README.md
└── ...
目录结构介绍
src/main/java/graphql/
:包含 GraphQL Java 的核心实现代码。execution/
:执行 GraphQL 查询的代码。language/
:解析 GraphQL 语言的代码。schema/
:定义 GraphQL 模式的代码。validation/
:验证 GraphQL 查询的代码。
src/main/resources/
:包含项目的资源文件,如配置文件等。src/test/java/graphql/
:包含测试代码。src/test/resources/
:包含测试资源文件。pom.xml
:Maven 项目的配置文件。README.md
:项目说明文档。
2. 项目的启动文件介绍
GraphQL Java 项目的启动文件通常是一个 Java 类,用于启动和配置 GraphQL 服务。以下是一个示例启动文件:
package com.example.graphql;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring;
public class GraphQLApplication {
public static void main(String[] args) {
String schema = "type Query{hello: String}";
SchemaParser schemaParser = new SchemaParser();
TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);
RuntimeWiring runtimeWiring = newRuntimeWiring()
.type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
.build();
SchemaGenerator schemaGenerator = new SchemaGenerator();
GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();
ExecutionResult executionResult = build.execute("{hello}");
System.out.println(executionResult.getData().toString());
}
}
启动文件介绍
GraphQLApplication
:主类,包含main
方法,用于启动 GraphQL 服务。SchemaParser
:解析 GraphQL 模式定义。TypeDefinitionRegistry
:存储模式定义。RuntimeWiring
:配置运行时数据获取器。SchemaGenerator
:生成可执行的 GraphQL 模式。GraphQL
:构建和执行 GraphQL 查询。
3. 项目的配置文件介绍
GraphQL Java 项目的配置文件通常是 pom.xml
和一些资源文件。以下是 pom.xml
的示例:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.
graphql-javaGraphQL Java implementation项目地址:https://gitcode.com/gh_mirrors/gr/graphql-java