加载可识别配置文件的YAML属性源资源

时间:2018-08-19 11:12:00

标签: spring spring-boot

在我的Spring Boot应用程序中,我希望基于Spring的客户端库配置位于与application{-PROFILE}.yml配置文件(即。{配置文件如下所示

resources/
    META-INF/
        spring.factories
    application.yml
    application-UAT.yml
    application-PROD.yml
    application-TEST.yml
    loggingServiceClient.yml
    loggingServiceClient-UAT.yml
    loggingServiceClient-PROD.yml
    loggingServiceClient-TEST.yml

Spring已经负责加载了解配置文件的应用程序YAML配置文件(我认为使用ConfigFileApplicationListener)。因此,要加载loggingServiceClient YAML配置文件,我通过实现ApplicationContextInitializer<ConfigurableApplicationContext>创建了自己的属性源,并创建了spring.factories以自动初始化初始化程序(请参见下文)。

我的问题: 是否有一种更优雅的方式来加载loggingServiceClient YAML配置并了解配置文件,而不是我的自定义代码将配置文件添加到文件名的末尾并以正确的顺序将其插入到“属性来源”列表中?

spring.factories

org.springframework.context.ApplicationContextInitializer=au.com.blah.api.client.logging.LoggingServiceClientInitialiser

初始化器

public class LoggingServiceClientInitialiser implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(final ConfigurableApplicationContext applicationContext) {
        try {
            addDefaultPropertySource(applicationContext);
            addProfilePropertySource(applicationContext);
        } catch (IOException ex) {
            throw new RuntimeException("Unable to load logging service client properties", ex);
        }
    }

    private void addDefaultPropertySource(final ConfigurableApplicationContext applicationContext) throws IOException {

        final Resource resource = applicationContext.getResource("classpath:loggingServiceClient.yml");
        final YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
        final PropertySource<?> yamlTestProperties = sourceLoader.load("loggingServiceClientDefault", resource, null);

        applicationContext.getEnvironment().getPropertySources().addFirst(yamlTestProperties);
    }

    private void addProfilePropertySource(final ConfigurableApplicationContext applicationContext) throws IOException {
        final String profile = Arrays.stream(applicationContext.getEnvironment().getActiveProfiles())
            .findFirst()
            .orElse(null);

        if (StringUtils.isBlank(profile)) {
            return;
        }

        final Resource resource = applicationContext.getResource("classpath:loggingServiceClient-" + profile + ".yml");
        final YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
        final PropertySource<?> yamlTestProperties = sourceLoader.load("loggingServiceClient" + profile, resource, null);

        applicationContext.getEnvironment().getPropertySources()
            .addBefore("loggingServiceClientDefault", yamlTestProperties);
    }
}

0 个答案:

没有答案