如何在Spring Boot中使用GraphQL
    		       		warning:
    		            这篇文章距离上次修改已过426天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中使用GraphQL,你需要做以下几步:
- 添加依赖:在pom.xml中添加Spring Boot的GraphQL依赖,例如使用graphql-spring-boot-starter。
<dependency>
    <groupId>com.graphql-java-kickstart</groupId>
    <artifactId>graphql-spring-boot-starter</artifactId>
    <version>10.0.0</version>
</dependency>- 定义GraphQL模式(Schema):在src/main/resources/graphql/schema.graphqls中定义GraphQL模式。
type Query {
  hello: String
}- 实现数据 fetcher:在src/main/java下创建一个类实现GraphQL的数据获取逻辑。
@Component
public class HelloFetcher implements DataFetcher<String> {
    @Override
    public String get(DataFetchingEnvironment environment) {
        return "Hello, GraphQL!";
    }
}- 配置GraphQL:在application.properties或application.yml中配置GraphQL相关设置。
# application.properties
spring.graphql.schema.printer.enabled=true
spring.graphql.cors.allowed-origins=*- 启动类:确保你的Spring Boot启动类上有@EnableGraphQl注解。
@SpringBootApplication
@EnableGraphQl
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}- 运行应用程序,并通过HTTP接口访问GraphQL。
这样,你就在Spring Boot应用中配置了GraphQL,并可以通过GraphQL引擎接口接收查询并返回数据。
评论已关闭