栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用环境覆盖Spring Cloud Config值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用环境覆盖Spring Cloud Config值

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;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/367517.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号