GraphQL:Spring Boot集成Graphql简单实例
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.DataFetcher;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class GraphQLApplication {
@Bean
public GraphQL graphQL() {
return GraphQL.newGraphQL(graphQLSchema()).build();
}
private GraphQLSchema graphQLSchema() {
return GraphQLSchema.newSchema()
.query(queryType())
.build();
}
private GraphQLObjectType queryType() {
return GraphQLObjectType.newObject()
.name("hello")
.field(field -> field
.name("world")
.type(GraphQLString)
.dataFetcher(helloWorldDataFetcher())
)
.build();
}
private DataFetcher<?> helloWorldDataFetcher() {
return dataFetchingEnvironment -> "Hello, World!";
}
public static void main(String[] args) {
SpringApplication.run(GraphQLApplication.class, args);
ExecutionResult executionResult = graphQL().execute("{ hello { world }}");
System.out.println(executionResult.getData());
}
}
这段代码定义了一个简单的GraphQL查询,当Spring Boot应用启动时,它会执行一个简单的GraphQL查询并打印结果。这个例子展示了如何在Spring Boot应用中集成GraphQL,并定义了一个GraphQL类型和查询。
评论已关闭