此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Boot 3.4.3spring-doc.cadn.net.cn

适用于 GraphQL 的 Spring

如果要构建 GraphQL 应用程序,可以利用 Spring Boot 对 Spring for GraphQL 的自动配置。 Spring for GraphQL 项目基于 GraphQL Java。 您将需要spring-boot-starter-graphqlstarter 的最小值。 由于 GraphQL 与传输无关,因此您还需要在应用程序中添加一个或多个额外的Starters,以便在 Web 上公开 GraphQL API:spring-doc.cadn.net.cn

起动机 运输 实现

spring-boot-starter-webspring-doc.cadn.net.cn

HTTP 协议spring-doc.cadn.net.cn

Spring MVCspring-doc.cadn.net.cn

spring-boot-starter-websocketspring-doc.cadn.net.cn

WebSocket 浏览器spring-doc.cadn.net.cn

用于 Servlet 应用程序的 WebSocketspring-doc.cadn.net.cn

spring-boot-starter-webfluxspring-doc.cadn.net.cn

HTTP、WebSocketspring-doc.cadn.net.cn

Spring WebFluxspring-doc.cadn.net.cn

spring-boot-starter-rsocketspring-doc.cadn.net.cn

TCP、WebSocketspring-doc.cadn.net.cn

Reactor Netty 上的 Spring WebFluxspring-doc.cadn.net.cn

GraphQL 架构

Spring GraphQL 应用程序在启动时需要定义的架构。 默认情况下,您可以在src/main/resources/graphql/**Spring Boot 将自动选取它们。 您可以使用spring.graphql.schema.locations和带有spring.graphql.schema.file-extensions.spring-doc.cadn.net.cn

如果您希望 Spring Boot 检测该位置的所有应用程序模块和依赖项中的 schema 文件, 您可以设置spring.graphql.schema.locations"classpath*:graphql/**/"(请注意classpath*:前缀)。

在以下部分中,我们将考虑此示例 GraphQL 架构,定义两种类型和两种查询:spring-doc.cadn.net.cn

type Query {
    greeting(name: String! = "Spring"): String!
    project(slug: ID!): Project
}

""" A Project in the Spring portfolio """
type Project {
    """ Unique string id used in URLs """
    slug: ID!
    """ Project name """
    name: String!
    """ URL of the git repository """
    repositoryUrl: String!
    """ Current support status """
    status: ProjectStatus!
}

enum ProjectStatus {
    """ Actively supported by the Spring team """
    ACTIVE
    """ Supported by the community """
    COMMUNITY
    """ Prototype, not officially supported yet  """
    INCUBATING
    """ Project being retired, in maintenance mode """
    ATTIC
    """ End-Of-Lifed """
    EOL
}
默认情况下,架构上将允许现场自省,因为 GraphiQL 等工具需要它。 如果您不想公开有关架构的信息,可以通过设置spring.graphql.schema.introspection.enabledfalse.

GraphQL 运行时布线

The GraphQL JavaRuntimeWiring.Builder可用于注册自定义标量类型、指令、类型解析器、DataFetcher等。 您可以声明RuntimeWiringConfigurerbeans 来访问RuntimeWiring.Builder. Spring Boot 会检测此类 bean 并将它们添加到 GraphQlSource 构建器中。spring-doc.cadn.net.cn

但是,应用程序通常不会实现DataFetcher直接创建带注释的控制器。 Spring Boot 将自动检测@Controller类,并将其注册为DataFetchers. 以下是我们的问候查询的示例实现,其中@Controller类:spring-doc.cadn.net.cn

import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {

	@QueryMapping
	public String greeting(@Argument String name) {
		return "Hello, " + name + "!";
	}

}
import org.springframework.graphql.data.method.annotation.Argument
import org.springframework.graphql.data.method.annotation.QueryMapping
import org.springframework.stereotype.Controller

@Controller
class GreetingController {

	@QueryMapping
	fun greeting(@Argument name: String): String {
		return "Hello, $name!"
	}

}

Querydsl and QueryByExample Repositories Support

Spring Data offers support for both Querydsl and QueryByExample repositories. Spring GraphQL can configure Querydsl and QueryByExample repositories as DataFetcher.spring-doc.cadn.net.cn

Spring Data repositories annotated with @GraphQlRepository and extending one of:spring-doc.cadn.net.cn

are detected by Spring Boot and considered as candidates for DataFetcher for matching top-level queries.spring-doc.cadn.net.cn

Transports

HTTP and WebSocket

The GraphQL HTTP endpoint is at HTTP POST /graphql by default. It also supports the "text/event-stream" media type over Server Sent Events for subscriptions only. The path can be customized with spring.graphql.http.path.spring-doc.cadn.net.cn

The HTTP endpoint for both Spring MVC and Spring WebFlux is provided by a RouterFunction bean with an @Order of 0. If you define your own RouterFunction beans, you may want to add appropriate @Order annotations to ensure that they are sorted correctly.

The GraphQL WebSocket endpoint is off by default. To enable it:spring-doc.cadn.net.cn

Spring GraphQL provides a Web Interception model. This is quite useful for retrieving information from an HTTP request header and set it in the GraphQL context or fetching information from the same context and writing it to a response header. With Spring Boot, you can declare a WebGraphQlInterceptor bean to have it registered with the web transport.spring-doc.cadn.net.cn

Spring MVC and Spring WebFlux support CORS (Cross-Origin Resource Sharing) requests. CORS is a critical part of the web config for GraphQL applications that are accessed from browsers using different domains.spring-doc.cadn.net.cn

Spring Boot supports many configuration properties under the spring.graphql.cors.* namespace; here’s a short configuration sample:spring-doc.cadn.net.cn

spring.graphql.cors.allowed-origins=https://example.org
spring.graphql.cors.allowed-methods=GET,POST
spring.graphql.cors.max-age=1800s
spring:
  graphql:
    cors:
      allowed-origins: "https://example.org"
      allowed-methods: GET,POST
      max-age: 1800s

RSocket

RSocket is also supported as a transport, on top of WebSocket or TCP. Once the RSocket server is configured, we can configure our GraphQL handler on a particular route using spring.graphql.rsocket.mapping. For example, configuring that mapping as "graphql" means we can use that as a route when sending requests with the RSocketGraphQlClient.spring-doc.cadn.net.cn

Spring Boot auto-configures a RSocketGraphQlClient.Builder<?> bean that you can inject in your components:spring-doc.cadn.net.cn

@Component
public class RSocketGraphQlClientExample {

	private final RSocketGraphQlClient graphQlClient;

	public RSocketGraphQlClientExample(RSocketGraphQlClient.Builder<?> builder) {
		this.graphQlClient = builder.tcp("example.spring.io", 8181).route("graphql").build();
	}
@Component
class RSocketGraphQlClientExample(private val builder: RSocketGraphQlClient.Builder<*>) {

And then send a request: include-code::RSocketGraphQlClientExample[tag=request]spring-doc.cadn.net.cn

Exception Handling

Spring GraphQL enables applications to register one or more Spring DataFetcherExceptionResolver components that are invoked sequentially. The Exception must be resolved to a list of GraphQLError objects, see Spring GraphQL exception handling documentation. Spring Boot will automatically detect DataFetcherExceptionResolver beans and register them with the GraphQlSource.Builder.spring-doc.cadn.net.cn

GraphiQL and Schema Printer

Spring GraphQL offers infrastructure for helping developers when consuming or developing a GraphQL API.spring-doc.cadn.net.cn

Spring GraphQL ships with a default GraphiQL page that is exposed at "/graphiql" by default. This page is disabled by default and can be turned on with the spring.graphql.graphiql.enabled property. Many applications exposing such a page will prefer a custom build. A default implementation is very useful during development, this is why it is exposed automatically with spring-boot-devtools during development.spring-doc.cadn.net.cn

You can also choose to expose the GraphQL schema in text format at /graphql/schema when the spring.graphql.schema.printer.enabled property is enabled.spring-doc.cadn.net.cn