当前位置:首页 > 单片机 > 架构师社区
[导读]前言在浅尝GraphQL一文描述了GraphQL及基本使用,本文提供一个基本示例,描述如何基于springboot的web项目快速应用。graphql-java的官方文档:GettingstartedwithGraphQLJavaandSpringBoot,提供了相关依赖用以快速...

前言

在浅尝GraphQL一文描述了GraphQL及基本使用,本文提供一个基本示例,描述如何基于spring boot的web项目快速应用。graphql-java的官方文档:Getting started with GraphQL Java and Spring Boot,提供了相关依赖用以快速配置,但是个人真心不建议使用这个库及相关配置方式来搭建脚手架,在实际开发中,业务比较复杂的时候,会导致需要配置的业务代码比较多也比较繁琐,相对下面这种方式,代码复杂性比较高。本文提供一种更灵活快捷的方式,在spring boot项目中快速应用开发。使用的依赖也和上面官方提供的都不一样,请注意区分。

快速开始

创建spring boot工程

通过Spring Initializr快速搭建,我选的jdk版本及spring boot版本,如下所示,其它版本未做兼容性测试。
Spring Boot   GraphQL 才是 API 的未来!
点击下方的Generate按钮:
Spring Boot   GraphQL 才是 API 的未来!
打开工程结构如下,我将application.properties删除了替换成applicaiton.yml,因为我个人比较喜欢yaml的配置方式:
Spring Boot   GraphQL 才是 API 的未来!

引入相关依赖

pom.xml配置如下:"1.0" encoding="UTF-8"?>
"http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4.0.0
 
  org.springframework.boot
  spring-boot-starter-parent
  2.4.6
   
 
 com.xuxd
 graphql.demo
 0.0.1-SNAPSHOT
 graphql.demo
 GraphQL Demo project for Spring Boot
 
  1.8
  1.8
  1.8
  UTF-8
  UTF-8
  1.18.20
  11.0.1
  2.8.7
 
 
  
   org.springframework.boot
   spring-boot-starter
  


  
   org.springframework.boot
   spring-boot-starter-web
  


  
   org.springframework.boot
   spring-boot-starter-test
   test
  


  
   org.projectlombok
   lombok
   ${lombok.version}
   provided
  


  
   com.graphql-java-kickstart
   graphql-java-tools
   ${graphql-java-tools.version}
  


  
   com.google.code.gson
   gson
   ${gson.version}
  

 


 
  
   
    org.springframework.boot
    spring-boot-maven-plugin
   
  
 



初始化GraphQL实例

我们将创建一个GraphQL实例并将其注册到spring容器中,代码如下。Spring Boot 基础就不介绍了,推荐下这个实战教程:https://www.javastack.cn/categories/Spring-Boot/创建一个GraphQLProvider类:@Component
public class GraphQLProvider {

    private GraphQL graphQL;

    @Autowired
    private IItemService itemService;

    @Bean
    public GraphQL graphQL() {
        return graphQL;
    }

    @PostConstruct
    public void init() throws IOException {
        GraphQLSchema graphQLSchema = SchemaParser.newParser()
            .file("graphql/base.graphqls")
            .resolvers(new Query(), new Mutation())
            .file("graphql/item.graphqls")
            .resolvers(new ItemResolver(itemService))
//            .file("book.graphqls")
//            .resolvers(new BookResolver())  //其它定义照上面的示例,继续增加
            .build().makeExecutableSchema();

        this.graphQL = graphQL.newGraphQL(graphQLSchema).build();
    }

}
关于*.graphqls或者对应的Resolver如ItemResolver,可以参看浅尝GraphQL相关描述,这里只是作了微调整,相关代码如下:base.grqphqlsschema {
    # 查询
    query: Query
    # 更新
    mutation: Mutation
}

type Query {
    version: String
}

type Mutation {
    version: String
}
item.graphqls# 定义一个查询类型
extend type Query {
    queryItemList: ItemList  # 定义查询项目列表
    queryById(id: ID): Item
}

extend type Mutation {
    updateName(param: Param): Item
}

# 定义项目字段
type Item {
    id: ID!
    code: String!
    name: String!
}

type ItemList {
    itemList: [Item!]!  #获取项目列表
    total: Int!      # 获取项目总数
}

input Param {
    id: ID!
    name: String!
}
ItemResolverpublic class ItemResolver implements GraphQLQueryResolver, GraphQLMutationResolver {

    private IItemService itemService;

    public ItemResolver(IItemService itemService) {
        this.itemService = itemService;
    }

    // 对应item.graphqls里的queryItemList
    public ItemList queryItemList() {
        return itemService.queryItemList();
    }

    public Item queryById(Long id) {
        return itemService.queryById(id);
    }

    public Item updateName(Param param) {
        return itemService.updateName(param);
    }
}
相关业务代码比较多,就不一一贴了。

提供API

 result = new HashMap<>();        ExecutionResult executionResult = graphQL.execute(executionInput);        List errors = executionResult.getErrors();        if (errors != null 
本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭