Quarkus Reactive Routes中POST请求RequestBody配置及Swagger显示问题
问题
通过Quarkus应用将请求转发至Hasura,编写了如下Reactive Routes路由代码:
@Route(path = "/v1/graphql", produces = "application/json", methods = Route.HttpMethod.POST) public Uni<Buffer> toHasura(RoutingContext rc, @Body String query) { // 转发逻辑 }
最初未添加@Body注解时,运行报错:
Caused by: java.lang.IllegalStateException: No parameter injector found for parameter 1 of route method io.smallrye.mutiny.Uni<io.vertx.mutiny.core.buffer.Buffer> toHasura(io.vertx.ext.web.RoutingContext rc, java.lang.String query) declared on CLASS bean [types=[org.acme.reactive.routes.ProxyRout, java.lang.Object], qualifiers=[@Default, @Any], target=org.acme.reactive.routes.ProxyRout]
添加@Body注解后错误消失,但Swagger页面中找不到添加请求体的入口。
解决方案
1. 确保引入OpenAPI扩展
首先确认项目中已添加Quarkus OpenAPI扩展依赖(quarkus-smallrye-openapi),如果未添加,在构建文件中加入:
Maven(pom.xml)
<dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-smallrye-openapi</artifactId> </dependency>
Gradle(build.gradle)
implementation 'io.quarkus:quarkus-smallrye-openapi'
2. 显式添加OpenAPI请求体注解
Reactive Routes的@Body注解不会自动被OpenAPI扫描识别,需要手动添加MicroProfile OpenAPI的@RequestBody注解,配合@Content和@Schema定义请求体结构:
import jakarta.ws.rs.core.MediaType; import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody; import org.eclipse.microprofile.openapi.annotations.media.Content; import org.eclipse.microprofile.openapi.annotations.media.Schema; @Route(path = "/v1/graphql", produces = "application/json", methods = Route.HttpMethod.POST) @RequestBody( content = @Content( mediaType = MediaType.APPLICATION_JSON, schema = @Schema(type = Schema.Type.STRING, description = "GraphQL查询语句") ), required = true ) public Uni<Buffer> toHasura(RoutingContext rc, @Body String query) { // 转发逻辑 }
3. (可选)使用DTO类定义请求体
如果需要更清晰的结构,可创建DTO类封装GraphQL请求,Swagger会自动识别请求体结构:
public class GraphQLRequest { @Schema(description = "GraphQL查询语句") private String query; // 生成getter、setter方法 }
修改路由方法:
@Route(path = "/v1/graphql", produces = "application/json", methods = Route.HttpMethod.POST) @RequestBody(required = true) public Uni<Buffer> toHasura(RoutingContext rc, @Body GraphQLRequest request) { String query = request.getQuery(); // 转发逻辑 }
完成修改后重启Quarkus应用,访问默认Swagger页面/q/swagger-ui/即可看到请求体输入入口。
内容的提问来源于stack exchange,提问作者Nancy Smith
相关产品推荐
相关产品推荐

