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

Quarkus扩展中@ConfigItem使用问题:配置List<Server>报错求助

解决方案:Quarkus @ConfigItem List 转换错误(SRCFG00013)

问题核心

Quarkus配置系统无法自动识别Server类型的转换规则,当使用List<Server>时,必须明确提供该类型的解析逻辑——要么将Server标记为配置组,要么自定义转换器。

方案1:将Server标记为@ConfigGroup

如果Server本身是一组配置项的集合,直接给它添加@ConfigGroup注解,Quarkus会自动支持列表形式的嵌套配置解析:

@ConfigGroup
public static class Server {
    @ConfigItem
    public String host;
    
    @ConfigItem(defaultValue = "8080")
    public int port;
}

@ConfigGroup
public static class Properties {
    @ConfigItem  
    public List<Server> servers = new ArrayList<>();
}

对应的配置文件格式(以application.properties为例):

# 假设Properties所属的配置根前缀为my.app
my.app.servers[0].host=localhost
my.app.servers[0].port=8080
my.app.servers[1].host=example.com
my.app.servers[1].port=9090

方案2:自定义Converter解析Server

如果Server是普通POJO,需要实现io.smallrye.config.Converter<Server>接口,定义字符串到Server的转换逻辑:

1. 实现Converter类

public class ServerConverter implements Converter<Server> {
    @Override
    public Server convert(String value) throws IllegalArgumentException {
        // 示例:从"host:port"格式解析为Server对象
        String[] parts = value.split(":");
        if (parts.length != 2) {
            throw new IllegalArgumentException("无效的Server格式:" + value + ",需符合host:port");
        }
        
        Server server = new Server();
        server.host = parts[0];
        server.port = Integer.parseInt(parts[1]);
        return server;
    }
}

2. 注册Converter

有两种注册方式:

  • 方式A:注解注册
    在Converter类上添加@jakarta.inject.Provider(或javax.inject.Provider,取决于Quarkus版本),Quarkus会自动扫描并加载。
  • 方式B:服务文件注册
    在项目src/main/resources/META-INF/services/目录下创建文件io.smallrye.config.Converter,文件内容为Converter的全类名:
    com.your.package.ServerConverter
    

3. 配置文件格式

此时配置可使用逗号分隔的字符串列表:

my.app.servers=localhost:8080,example.com:9090

关键注意点

  • 配置键的层级必须与你的配置类结构匹配,比如Properties若属于某个@ConfigRoot注解的类,配置键要以该根的前缀开头。
  • 单个Server能正常工作是因为Quarkus可自动处理单个实例的嵌套配置解析,但列表形式需要明确的批量转换规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:47:18