java - 使用环境覆盖 Spring Cloud Config 值

标签 java spring spring-boot cloud-foundry spring-cloud

有没有办法用另一个属性源(特别是系统环境)覆盖通过 Spring Cloud Config Server 设置的属性?我知道我可以通过遍历 Environment 对象的 PropertySource 来手动完成它,但是如果我可以设置它以便 bootstrapConfig 源是最低优先级,这将是理想的。

最佳答案

FWIW,我通过编写一个自定义 ApplicationListener 来完成此操作,其事件在周期的早期触发,但在加载配置服务的 PropertySource 之后。如果有人感兴趣,我已在此处附上代码。如果有一个“官方”的 Spring 方法来做到这一点,我仍然很感兴趣,但这有效:

package com.example;

import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

@Order(Ordered.HIGHEST_PRECEDENCE)
public class ConfigServicePropertyDeprioritizer
        implements ApplicationListener<ApplicationPreparedEvent>
{
    private static final String CONFIG_SOURCE = "bootstrap";

    private static final String PRIORITY_SOURCE = "systemEnvironment";

    @Override
    public void onApplicationEvent(ApplicationPreparedEvent event)
    {
        ConfigurableEnvironment environment = event.getApplicationContext()
                .getEnvironment();
        MutablePropertySources sources = environment.getPropertySources();
        PropertySource<?> bootstrap = findSourceToMove(sources);

        if (bootstrap != null)
        {
            sources.addAfter(PRIORITY_SOURCE, bootstrap);
        }
    }

    private PropertySource<?> findSourceToMove(MutablePropertySources sources)
    {
        boolean foundPrioritySource = false;

        for (PropertySource<?> source : sources)
        {
            if (PRIORITY_SOURCE.equals(source.getName()))
            {
                foundPrioritySource = true;
                continue;
            }

            if (CONFIG_SOURCE.equals(source.getName()))
            {
                // during bootstrapping, the "bootstrap" PropertySource
                // is a simple MapPropertySource, which we don't want to
                // use, as it's eventually removed. The real values will 
                // be in a CompositePropertySource
                if (source instanceof CompositePropertySource)
                {
                    return foundPrioritySource ? null : source;
                }
            }
        }

        return null;
    }
}

关于java - 使用环境覆盖 Spring Cloud Config 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31551039/

相关文章:

java - 无法 Autowiring 。未找到 'NoteRepository' 类型的 beans

java - 方法完成后立即提交事务

java - 在 Spring Boot Thymeleaf Controller 返回的 View 中显示字符串

java - java中如何从字符串中去掉字符串?

java - 查找导入的变量来自哪里

java - Spring Boot Autowiring 实体管理器特定于配置

java - 使用 Ext JS 6 下载文件

java - 从后台运行启动服务程序的命令(通过命令行)

java - 中间表和非主键的一对一映射

java - 循环,迭代得到意想不到的结果