
专注分享最新技术内容

总结
在这篇文章中,将带你在Spring Boot项目中一步一步集成graphql,其中关键的步骤和相关的配置会进行提供。
准备工作
你需要检查自己的环境是否满足以下前提。你可以打开终端,使用以下命令检测自己是否已经安装JDK 、Kotlin 和 gradle 。
$ kotlin -version
## output: Kotlin version 1.3.61-release-180 (JRE 13.0.2+8)
$ javac -version
## output: javac 13.0.2
$ gradle -version
使用 Spring Boot Initializr 生成项目
访问 https://start.spring.io/ , 选择如下的环境:
Project: Gradle Project Language: Kotlin Spring Boot: 2.2.5 Group: com.springforall Artifact: graphqlDemo Dependencies: Spring Web, Spring Boot DevTools
选择完成之后,点击生成按钮。
添加依赖
我们需要添加GraphQL的相关依赖和工具。
// file build.gradle.kts
dependencies {
implementation ("com.graphql-java:graphql-spring-boot-starter:5.0.2")
implementation ("com.graphql-java:graphiql-spring-boot-starter:5.0.2")
implementation ("com.graphql-java:voyager-spring-boot-starter:5.0.2")
implementation ("com.graphql-java:graphql-java-tools:5.2.4")
... rest of dependencies
}
这里我们已经在项目中集成了 graphql, https://github.com/graphql/graphiql#graphiql, https://github.com/APIs-guru/graphql-voyager 这些工具可以更好的帮助你使用GraphiQL设计类的关系和结构。
修改应用配置
通过上面添加依赖后,我们需要对GraphiQL做相关的配置。创建一个配置文件,配置文件的名称根据约定优于配置的原则,暂且命名为 application.yml
在 ./src/main/resources
# file application.yml
graphql:
servlet:
mapping: graphql
enabled: true
corsEnabled: true
graphiql:
mapping: graphiql
endpoint: graphql
enabled: true
pageTitle: GraphiQL
cdn:
enabled: false
version: 0.11.11
数据模型
现在我们创建一个数据模型类,类名为Book,此类包含两个属性。
package com.springforall.graphqlDemo
data class Book( val id: String, val name: String )
// file: ./src/main/kotlin/com/grekz/graphqlDemo/Book.kt
创建 GraphQL 查询解析器
package com.springforall.graphqlDemo
import org.springframework.stereotype.Component
import com.coxautodev.graphql.tools.GraphQLQueryResolver
@Component
class BookResolver() : GraphQLQueryResolver {
this method name needs to be same and in the schema
fun books(): List<Book> {
val book1 = Book("1", "name1")
val book2 = Book("2", "name2")
return listOf(book1, book2)
}
}
// file: ./src/main/kotlin/com/springforall/graphqlDemo/BookResolver.kt
定义 GraphQL schema
在 GraphQL 中,需要定义类型和数据如何被查询的规则。接下来在./src/main/resources/models.graphqls
进行相关定义。
type Query {
books: [Book]
}
type Book {
id: String!
name: String!
}
运行项目!
接下来我们开始运行项目,验证结果。可以使用如下命令启动项目:
$ gradle bootRun
也可以点击 “Debug” 按钮运行,验证结果。访问: http://localhost:8080/voyager ,检查是否正常。
这样我们便完成了在SpringBoot中如何集成 GraphQL 并运行。

一杯热茶一行代码,加个关注加份知识~


我好想知道,你在看吗?~~~

文章转载自锅外的大佬,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




