GraphQL 是什么这里我们就不做描述,想了解的可以直接点击链接查阅。
我们直接说明如何在 Spring Boot 框架中使用 GraphQL。
1 引入依赖
在 pom.xml 引入依赖就:
<!-- 必需:包含了默认配置、graphql-java 和 graphql-java-tools,可以简化配置 -->
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>11.0.0</version>
</dependency>
<!-- 可选:用于调试 GraphQL,功能类似 Restful 中的 Swagger -->
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>playground-spring-boot-starter</artifactId>
<version>11.0.0</version>
</dependency>
2 配置
如果第1步没有引入playground-spring-boot-starter依赖,而是使用浏览器的 GraphQL Playground 插件调试 GraphQL,则还需要关闭跨域。如下 application.yml 文件:
graphql:
servlet:
corsEnabled: false # 关闭跨域,仅使用浏览器插件调试时设置为false
playground:
cdn:
enabled: true # playground 使用 cdn 的静态文件
如果没有关闭跨域,那么用浏览器插件调用接口会返回 403 Forbidden,并提示错误:
{
"error": "Unexpected token I in JSON at position 0"
}
更多配置请参考《Enable GraphQL Servlet》。
3 编写schema文件
创建文件:src/main/resources/graphql/schema.graphqls,注意文件后缀必须是 .graphqls。内容:
type Query {
questionById(id: ID): Question
}
type Question {
id: ID
title: String
content: String
userId: Int
}
这了定义了一个查询,名为questionById,其参数为id。
4 编写Java代码
创建文件:src/main/java/org/termi/community/resolver/Query.java,内容:
package org.termi.community.resolver;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.termi.community.model.Question;
import org.termi.community.service.question.QuestionService;
@Component
public class Query implements GraphQLQueryResolver {
@Autowired
private QuestionService questionService;
public Question getQuestionById(long id) {
return questionService.selectById(id);
}
}
这里的 getQuestionById 方法对应 schema 文件中的 questionById这个Query。
同时,我们要查询数据,所以注入了 QuestionService,具体的查询功能需要自己实现,必须要返回一个Question对象。
package org.termi.community.model;
@Data
public class Question {
private Long id;
private String title;
private String content;
private Integer userId;
}
5 启动测试
启动 Spring Boot。
在浏览器地址栏中输入 http://localhost:8080/playground,输入以下查询命令:
{
questionById(id: 126628556787679232) {
id
title
content
userId
}
}
点中间的执行按钮就可以看到结果了。
与 playground 拥有类似作用的还有 graphiql 和 voyager,具体可参项目介绍的《Documentation》。
参考资料:
- graphql-java-kickstart/graphql-spring-boot:https://github.com/graphql-java-kickstart/graphql-spring-boot
- graphql-java使用记录:https://segmentfault.com/a/1190000020309793
