首页 > 解决方案 > 使用动态配置键的 Microprofile 配置

问题描述

我目前正在寻找一种动态组装配置键(回退处理)的方法,然后在我们的 microprofile-config.properties 文件中查找它们。这样的文件可能如下所示:

# customer fallbacks

my.config=1234                            # use this fallback when there is no customer
customer2.my.config=12345                 # use this fallback when there is no subcustomer
customer2.subCustomer1.my.config=123456   # first level

所以当有一个客户和一个子客户时,然后使用 on

我遇到这个问题的原因是我想使用@ConfigProperty注释,所以没有 ConfigProvider.getConfig()。这意味着我将不得不在我的 custom 中组装我的动态配置密钥ConfigSource

我知道 ConfigSources 是通过 ServiceLoader 在服务器启动时加载的。所以我尝试删除现有的配置并将其替换为我的自定义配置:

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;

@Startup
@Singleton
public class StartupConfigurationRegistrar{

@PostConstruct
private void registerConfig() {
        final Config customConfig = ConfigProviderResolver.instance().getBuilder().withSources(new FallbackHandlingConfiguration(myReqiredVariables)).addDefaultSources().build();
        ConfigProviderResolver.instance().releaseConfig(ConfigProviderResolver.instance().getConfig());
        ConfigProviderResolver.instance().registerConfig(customConfig, Thread.currentThread().getContextClassLoader());
    }
}

我的 ConfigSource 已正确添加。但是后来当尝试访问不同类中的配置时,我的自定义ConfigSource消失了,只剩下三个默认的 ConfigSource。我认为这可能是一个 ClassLoader 问题。

任何想法如何在 a 中获取动态值ConfigSource

标签: jakarta-eeconfigmicroprofile

解决方案


你对ConfigBuilder. 如果您使用它来创建一个,Config那么您必须手动传递它。

但大多数时候您通常使用我们的“自动发现”模式。这适用于标准java.util.ServiceLoader机制。它在规范 PDF 以及 JavaDocs 中进行了描述:https ://github.com/eclipse/microprofile-config/blob/master/api/src/main/java/org/eclipse/microprofile/config/spi/ ConfigSource.java#L64

但我宁愿没有具有动态值的 ConfigSource,因为这可能会在高并发负载下造成麻烦。您可能更愿意看看addLookupSuffix我们为 ConfigJSR 提出的机制,现在正在移植回 mp-config: https ://github.com/eclipse/ConfigJSR/blob/master/api/src/main/java/javax/配置/ConfigAccessor.java#L191

它与您最初的想法相似,但 .customer2 将是 config 键的后缀。hth。


推荐阅读