在Spring Boot中集成GraphQL查询,你需要遵循以下步骤:
在你的pom.xml
文件中添加以下依赖:
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>11.1.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>11.1.0</version>
</dependency>
创建一个GraphQL schema文件,例如schema.graphqls
,并将其放在src/main/resources/graphql
目录下。在这个文件中定义你的类型、查询和突变:
type Query {
hello: String
}
创建一个配置类,例如GraphQLConfig.java
,并继承GraphQLSpringBootConfiguration
类。在这个类中,你需要配置GraphQL的Schema文件路径:
import com.coxautodev.graphql.tools.SchemaParser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.execution.GraphQLQueryResolver;
import org.springframework.graphql.execution.GraphQLMutationResolver;
import org.springframework.graphql.schema.GraphQLSchema;
import org.springframework.graphql.schema.idl.RuntimeWiring;
import org.springframework.graphql.schema.idl.SchemaGenerator;
import org.springframework.graphql.schema.idl.TypeRuntimeWiring;
@Configuration
public class GraphQLConfig {
@Bean
public GraphQLSchema graphQLSchema() {
SchemaParser schemaParser = new SchemaParser();
schemaParser.setResourceDirectory(new ClassPathResource("graphql"));
return schemaParser.parse();
}
@Bean
public RuntimeWiring runtimeWiring() {
return RuntimeWiring.newRuntimeWiring()
.type(TypeRuntimeWiring.newTypeWiring("Query")
.dataFetcher("hello", new GraphQLQueryResolver() {
@Override
public String hello() {
return "Hello, GraphQL!";
}
}))
.build();
}
}
创建一个控制器,例如GraphQLController.java
,并添加一个POST请求映射,以便客户端可以通过HTTP POST请求执行GraphQL查询:
import org.springframework.graphql.execution.GraphQLQueryResolver;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GraphQLController implements GraphQLQueryResolver {
@PostMapping("/graphql")
public String graphQL(@RequestBody String query) {
return query;
}
}
现在,你已经成功地在Spring Boot中集成了GraphQL查询。你可以通过发送一个包含GraphQL查询的POST请求到/graphql
端点来测试它。例如,使用curl发送请求:
curl -X POST -H "Content-Type: application/json" -d '{"query": "{ hello }"}' http://localhost:8080/graphql
响应应该是:
{
"data": {
"hello": "Hello, GraphQL!"
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。