You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Quarkus RestClient如何实现@BeanParam等效功能?用POJO传多参数

在Quarkus RestClient中使用POJO替代Map传递可选查询参数

完全可以实现,具体方案如下:

1. 定义查询参数POJO

创建一个POJO类,每个属性对应一个可选查询参数,用@RestQuery注解标记每个属性。可选参数可以用Optional类型或者允许字段为null,未赋值的参数不会被添加到请求的查询字符串中。

import org.eclipse.microprofile.rest.client.annotation.RestQuery;
import java.util.Optional;

public class ExtensionFilter {
    @RestQuery
    private Optional<String> name;
    
    @RestQuery
    private Optional<String> category;
    
    @RestQuery
    private Integer minVersion;

    // 生成getter、setter,或用Lombok简化
    public Optional<String> getName() { return name; }
    public void setName(Optional<String> name) { this.name = name; }
    public Optional<String> getCategory() { return category; }
    public void setCategory(Optional<String> category) { this.category = category; }
    public Integer getMinVersion() { return minVersion; }
    public void setMinVersion(Integer minVersion) { this.minVersion = minVersion; }
}

2. 在RestClient接口中使用该POJO

直接将POJO作为方法参数传入,无需额外注解(每个字段已通过@RestQuery指定参数映射):

import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
import java.util.Set;
import javax.ws.rs.GET;

@RegisterRestClient(baseUri = "/api/extensions")
public interface ExtensionClient {
    @GET
    Set<Extension> getByFilter(ExtensionFilter filter);
}

3. 调用示例

初始化POJO并设置需要的参数,未设置的参数会被自动忽略:

ExtensionFilter filter = new ExtensionFilter();
filter.setName(Optional.of("quarkus-rest-client"));
filter.setMinVersion(2);

Set<Extension> extensions = extensionClient.getByFilter(filter);

这会生成类似/api/extensions?name=quarkus-rest-client&minVersion=2的请求,未设置的category参数不会出现在查询字符串中。

原理说明

Quarkus的MicroProfile RestClient支持这种POJO参数映射,会自动遍历POJO中带有@RestQuery注解的属性,将非空(或非Optional.empty())的属性转换为URL查询参数,完美匹配你用POJO简化方法签名、处理可选参数的需求。

内容的提问来源于stack exchange,提问作者Snappawapa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 13:07:12