Java 与 GraphQL API 入门
GraphQL 是一种 API 查询语言,允许客户端仅请求其真正需要的数据。与每个端点返回固定数据结构的 REST 不同,GraphQL 提供了灵活性并减少了请求数量。在本教程中,我们将使用 Spring Boot 和 graphql-java 库在 Java 中创建一个完整的 GraphQL API。您将学习如何配置项目、定义模式、编写解析器以及处理查询和变更。所有代码示例均可直接运行。
1. 项目配置与依赖
首先,创建一个新的 Spring Boot 项目。我们将使用 Maven,但您可以将其适配到 Gradle。在 pom.xml 中添加以下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><dependency> <groupId>com.graphql-java</groupId> <artifactId>graphql-java</artifactId> <version>21.0</version></dependency><dependency> <groupId>com.graphql-java</groupId> <artifactId>graphql-java-spring-boot-starter-webmvc</artifactId> <version>2021-06-28T00-00-00-6e3b7b2</version></dependency>添加依赖后,创建主应用程序类:
@SpringBootApplicationpublic class GraphqlApplication { public static void main(String[] args) { SpringApplication.run(GraphqlApplication.class, args); }}现在配置 GraphQL 入口点。在 resources 文件夹中创建 application.yml 文件:
graphql: servlet: mapping: /graphql enabled: true cors-enabled: true完成!项目基本结构已启动。接下来我们进入模式定义阶段。
2. 定义 GraphQL 模式
模式是 GraphQL API 的核心。它描述了数据类型、查询和变更。在 src/main/resources 文件夹中创建 schema.graphqls 文件:
type Book { id: ID! title: String! author: String! year: Int}
type Query { books: [Book] bookById(id: ID!): Book}
type Mutation { addBook(title: String!, author: String!, year: Int): Book deleteBook(id: ID!): Boolean}这里我们定义了:
- Book — 包含 id、title、author 和 year 字段的对象。
- Query — 数据读取入口点(书籍列表和按 ID 查询)。
- Mutation — 数据修改操作(添加和删除书籍)。
现在我们需要将此模式加载到应用程序中。创建一个配置类:
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;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 java.io.File;import java.io.IOException;
@Configurationpublic class GraphqlConfig {
@Bean public GraphQL graphQL() throws IOException { File schemaFile = new File("src/main/resources/schema.graphqls"); TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(schemaFile); RuntimeWiring wiring = buildWiring(); GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(typeRegistry, wiring); return GraphQL.newGraphQL(schema).build(); }
private RuntimeWiring buildWiring() { return RuntimeWiring.newRuntimeWiring() .type(