此版本仍在开发中,尚未被认为是稳定的。请使用最新稳定版本 Spring GraphQL 2.0.2spring-doc.cadn.net.cn

GraphiQL

GraphiQL 是一个基于浏览器的图形化交互式 GraphQL IDE。 它在开发者中非常流行,因为它使探索和互动性地开发 GraphQL API 变得很容易。 在开发过程中,通常只需要标准的 GraphiQL 集成即可帮助开发者工作于 API 上。 而在生产环境中,应用程序可能需要带有公司标志或特定身份验证支持的自定义 GraphiQL 构建。spring-doc.cadn.net.cn

Spring for GraphQL 附带了一个 基于静态资源的 GraphiQL index.html 页面,这些资源托管在 esm.sh CDN 上。 Spring Boot 应用程序可以通过 配置属性轻松启用该页面spring-doc.cadn.net.cn

您的应用程序可能需要一个自定义的GraphiQL构建,如果它需要一种不依赖于CDN(内容分发网络)的设置,或者您希望自定义用户界面。 这可以通过两个步骤完成:spring-doc.cadn.net.cn

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

  2. 通过Spring web基础设施暴露构建好的GraphiQL实例spring-doc.cadn.net.cn

创建自定义 GraphiQL 构建

此部分内容通常超出了本文档的范围,因为有多种自定义构建选项。 您可以在 官方 GraphiQL 文档 中找到更多相关信息。 您可以选择直接将构建结果复制到应用程序资源中。 或者,您可以利用 Node.js GradleMaven 构建插件将 JavaScript 构建集成到您的项目中作为独立模块。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请求的Web处理器;您可以根据您的使用场景实现一个自定义的HandlerFunction
3 最后,将处理器映射到特定的HTTP端点
4 通过一个RouterFunction bean暴露出这个新的路由

您可能还需要配置应用程序以提供相关静态资源spring-doc.cadn.net.cn