对于最新稳定版本,请使用 Spring GraphQL 2.0.0spring-doc.cadn.net.cn

GraphiQL

GraphiQL 是一款图形交互式浏览器内 GraphQL 集成开发环境。 它在开发者中非常受欢迎,因为它使探索和交互式开发 GraphQL API 变得容易。 在开发过程中,默认的GraphiQL集成通常足以帮助开发者开发API。 在生产环境中,应用程序可能需要定制的 GraphiQL 构建,带有公司标志或特定的认证支持。spring-doc.cadn.net.cn

Spring for GraphQL 自带一台标配的GraphiQLindex.html使用托管在 unpkg.com CDN上的静态资源。 Spring Boot 应用程序可以轻松启用该页面,并带有配置属性spring-doc.cadn.net.cn

如果你的应用需要不依赖CDN的设置,或者你想自定义用户界面,可能需要定制GraphiQL构建。 这可以通过两个步骤完成:spring-doc.cadn.net.cn

  1. 配置并编译 GraphiQL 构建spring-doc.cadn.net.cn

  2. 通过 Spring Web 基础设施公开构建的 GraphiQL 实例spring-doc.cadn.net.cn

创建自定义 GraphiQL 构建

这部分通常不在文档的范围内,因为有多种自定义构建选项。 你可以在官方GraphiQL文档中找到更多信息。 你可以选择直接复制构建结果到应用资源中。 或者,你也可以利用 GradleMaven 的构建插件,将 JavaScript 构建集成到你的项目中作为独立模块Node.js。spring-doc.cadn.net.cn

暴露 GraphiQL 实例

一旦 GraphiQL 构建在类路径上可用,你可以将其作为端点与功能性 Web 框架一起暴露。spring-doc.cadn.net.cn

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.graphql.server.webmvc.GraphiQlHandler;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;

@Configuration
public class GraphiQlConfiguration {

	@Bean
	@Order(0)
	public RouterFunction<ServerResponse> graphiQlRouterFunction() {
		RouterFunctions.Builder builder = RouterFunctions.route();
		ClassPathResource graphiQlPage = new ClassPathResource("graphiql/index.html"); (1)
		GraphiQlHandler graphiQLHandler = new GraphiQlHandler("/graphql", "", graphiQlPage); (2)
		builder = builder.GET("/graphiql", graphiQLHandler::handleRequest); (3)
		return builder.build(); (4)
	}
}
1 从类路径加载 GraphiQL 页面(这里我们使用的是 Spring for GraphQL 预发的版本)
2 配置一个用于处理HTTP请求的网页处理程序;你可以实现自定义HandlerFunction这取决于你的使用场景
3 最后,将处理器映射到特定的HTTP端点
4 通过一个路由器功能

你可能还需要配置应用来服务相关的静态资源spring-doc.cadn.net.cn