您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。