您好,登錄后才能下訂單哦!
在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>
創(chuàng)建一個(gè)GraphQL schema文件,例如schema.graphqls
,并將其放在src/main/resources/graphql
目錄下。在這個(gè)文件中定義你的類型、查詢和突變:
type Query {
hello: String
}
創(chuàng)建一個(gè)配置類,例如GraphQLConfig.java
,并繼承GraphQLSpringBootConfiguration
類。在這個(gè)類中,你需要配置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();
}
}
創(chuàng)建一個(gè)控制器,例如GraphQLController.java
,并添加一個(gè)POST請(qǐng)求映射,以便客戶端可以通過HTTP POST請(qǐng)求執(zhí)行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;
}
}
現(xiàn)在,你已經(jīng)成功地在Spring Boot中集成了GraphQL查詢。你可以通過發(fā)送一個(gè)包含GraphQL查詢的POST請(qǐng)求到/graphql
端點(diǎn)來測試它。例如,使用curl發(fā)送請(qǐng)求:
curl -X POST -H "Content-Type: application/json" -d '{"query": "{ hello }"}' http://localhost:8080/graphql
響應(yīng)應(yīng)該是:
{
"data": {
"hello": "Hello, GraphQL!"
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。