使用动态配置键进行Microprofile配置

时间:2018-09-07 10:48:39

标签: java-ee config 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()。这意味着我将不得不在我的自定义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消失了,只剩下了三个默认的ConfigSources。我认为这可能是ClassLoader问题。

有什么想法如何在ConfigSource内获取动态值?

1 个答案:

答案 0 :(得分:0)

您对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,因为这可能在高并发负载下引起麻烦。 您可能希望看看我们为ConfigJSR提出的addLookupSuffix机制,现在正移植回mp-config: https://github.com/eclipse/ConfigJSR/blob/master/api/src/main/java/javax/config/ConfigAccessor.java#L191

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