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

Quarkus如何根据应用配置属性动态注入Repository的不同实现类

方案1:运行时配置切换(改配置重启即生效,适配你的yml配置场景)

这种方案不需要修改现有业务注入逻辑,仅需少量注解调整即可实现根据storage-type配置自动选择实现类:

  1. 给两个ExampleRepository实现类添加@Alternative注解,标记为备选实现,避免启动时依赖歧义报错:
@Alternative
@ApplicationScoped
public class DynamoRepository implements ExampleRepository {
    // 原有逻辑保持不变
}
@Alternative
@ApplicationScoped
public class CsvRepository implements ExampleRepository {
    // 原有逻辑保持不变
}
  1. 新增CDI Producer类,根据配置动态生成目标实现类的Bean实例:
import org.eclipse.microprofile.config.inject.ConfigProperty;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;

@ApplicationScoped
public class ExampleRepositoryProducer {

    @ConfigProperty(name = "com.example.application.storage-type")
    String storageType;

    @Inject
    DynamoRepository dynamoRepository;

    @Inject
    CsvRepository csvRepository;

    @Produces
    @ApplicationScoped
    public ExampleRepository produceRepository() {
        return switch (storageType) {
            case "AMAZON_DYNAMO_DB" -> dynamoRepository;
            case "CSV" -> csvRepository;
            default -> throw new IllegalArgumentException("非法存储类型配置: " + storageType);
        };
    }
}

配置完成后原有ExampleService的注入逻辑无需任何改动,启动时Quarkus会自动根据你yml里的storage-type值注入对应实现。


方案2:构建Profile切换(打包/启动时指定Profile即可切换)

如果你不需要运行时改配置切换,仅需根据构建/启动Profile选择实现,无需写Producer类,直接给实现类加Profile匹配注解即可:

// 仅在prod Profile生效
@IfBuildProfile("prod")
@ApplicationScoped
public class DynamoRepository implements ExampleRepository {}
// 仅在dev Profile生效
@IfBuildProfile("dev")
@ApplicationScoped
public class CsvRepository implements ExampleRepository {}

启动时指定quarkus.profile=dev或者quarkus.profile=prod即可自动切换对应实现,也可以在配置文件里配置quarkus.profile属性指定默认Profile。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:15:05