小编典典

使用环境覆盖Spring Cloud Config值

spring-boot

有没有一种方法可以使用另一个属性源(特别是系统环境)覆盖通过Spring Cloud Config
Server设置的属性?我知道我可以通过遍历Environment对象的PropertySources
来手动执行此操作,但是如果可以将其设置为使bootstrapConfig源成为最低优先级,那将是理想的选择。


阅读 527

收藏
2020-05-30

共1个答案

小编典典

FWIW,我通过编写一个自定义ApplicationListener事件来实现此目的,该自定义事件在周期的早期触发,但在Config Service
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;
    }
}
2020-05-30