如何在Quarkus中采用契约优先方式构建GraphQL API?
在Quarkus中实现GraphQL契约优先开发(基于SmallRye GraphQL)
一、准备GraphQL契约文件
先定义你的GraphQL Schema(.graphqls),建议放在src/main/resources/graphql/目录下,示例:
type Query { getUser(id: ID!): User } type User { id: ID! name: String! email: String }
二、选择代码生成工具
推荐用GraphQL Java Generator Maven插件,它能直接生成符合SmallRye GraphQL规范的服务端代码,适配Quarkus环境。
步骤1:配置Maven依赖与插件
在pom.xml中添加必要的依赖和插件:
1. 引入Quarkus SmallRye GraphQL扩展
<dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-smallrye-graphql</artifactId> </dependency>
2. 添加GraphQL代码生成插件
<build> <plugins> <plugin> <groupId>com.graphql-java-generator</groupId> <artifactId>graphql-maven-plugin</artifactId> <version>2.2.1</version> <!-- 使用最新稳定版 --> <executions> <execution> <goals> <goal>generateServerCode</goal> </goals> </execution> </executions> <configuration> <schemaFile>src/main/resources/graphql/schema.graphqls</schemaFile> <packageName>com.example.graphql.generated</packageName> <generateServerInterface>true</generateServerInterface> <customScalars> <customScalar> <scalarName>ID</scalarName> <javaType>java.lang.String</javaType> </customScalar> </customScalars> </configuration> </plugin> </plugins> </build>
步骤2:生成服务端代码
执行Maven命令触发代码生成:
mvn clean compile
插件会自动生成两类代码:
- 数据模型类(如
User.java) - 带SmallRye GraphQL注解的服务接口(如
Query.java)
三、实现生成的接口
创建业务实现类,继承生成的接口并编写逻辑:
package com.example.graphql; import com.example.graphql.generated.Query; import com.example.graphql.generated.User; import jakarta.enterprise.context.ApplicationScoped; @ApplicationScoped public class UserQueryService implements Query { @Override public User getUser(String id) { // 替换为实际业务逻辑,比如从数据库查询 return new User(id, "John Doe", "john.doe@example.com"); } }
四、运行与测试
启动Quarkus开发模式:
mvn quarkus:dev
访问http://localhost:8080/q/graphql-ui打开GraphQL Playground,即可测试你的API。
替代方案:SmallRye原生代码生成
如果不想用第三方插件,可直接借助SmallRye GraphQL的内置代码生成能力,在application.properties中添加配置:
smallrye.graphql.codegen.enabled=true smallrye.graphql.codegen.schema-locations=src/main/resources/graphql/ smallrye.graphql.codegen.package-name=com.example.graphql.generated
编译时SmallRye会自动生成模型和基础接口,你只需要实现业务逻辑即可。
内容的提问来源于stack exchange,提问作者nik0x1
相关产品推荐
相关产品推荐

