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

如何管理共享库中的spring-cloud bootstrap属性?

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

如何管理共享库中的spring-cloud bootstrap属性?

我能够找到解决方案。该解决方案的目标是:

  • 从共享库中的yaml文件加载值。
  • 允许使用该库的应用程序引入自己的bootstrap.yml,并将它们也加载到环境中。
  • bootstrap.yml中的值应覆盖共享yaml中的值。

主要挑战是在应用程序生命周期的适当时间点注入一些代码。具体来说,我们需要在将bootstrap.yml
PropertySource添加到环境中之后执行此操作(以便我们可以按照相对于它的正确顺序注入自定义PropertySource),但也需要在应用程序开始配置Bean之前(作为配置值控件)行为)。

我发现的解决方案是使用自定义的EnvironmentPostProcessor

public class CloudyConfigEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {    private YamlPropertySourceLoader loader;    public CloudyConfigEnvironmentPostProcessor() {        loader = new YamlPropertySourceLoader();    }    @Override    public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication application) {        //ensure that the bootstrap file is only loaded in the bootstrap context        if (env.getPropertySources().contains("bootstrap")) { //Each document in the multi-document yaml must be loaded separately. //Start by loading the no-profile configs... loadProfile("cloudy-bootstrap", env, null); //Then loop through the active profiles and load them. for (String profile: env.getActiveProfiles()) {     loadProfile("cloudy-bootstrap", env, profile); }        }    }    private void loadProfile(String prefix, ConfigurableEnvironment env, String profile) {        try { PropertySource<?> propertySource = loader.load(prefix + (profile != null ? "-" + profile: ""), new ClassPathResource(prefix + ".yml"), profile); //propertySource will be null if the profile isn't represented in the yml, so skip it if this is the case. if (propertySource != null) {     //add PropertySource after the "applicationConfigurationProperties" source to allow the default yml to override these.     env.getPropertySources().addAfter("applicationConfigurationProperties", propertySource); }        } catch (IOException e) { throw new RuntimeException(e);        }    }    @Override    public int getOrder() {        //must go after ConfigFileApplicationListener        return Ordered.HIGHEST_PRECEDENCE + 11;    }}

可以通过meta-INF / spring.factories注入此自定义的EnvironmentPostProcessor:

#Environment PostProcessorsorg.springframework.boot.env.EnvironmentPostProcessor=com.mycompany.cloudy.bootstrap.autoconfig.CloudyConfigEnvironmentPostProcessor

需要注意的几件事:

  • YamlPropertySourceLoader按配置文件加载yaml属性,因此,如果您使用的是多文档yaml文件,则实际上需要分别从其中分别加载每个配置文件,包括无配置文件的配置。
  • ConfigFileApplicationListener是EnvironmentPostProcessor,负责将bootstrap.yml(或常规上下文中的application.yml)加载到环境中,因此,为了相对于bootstrap.yml属性正确地优先放置自定义yaml属性,您需要对命令进行排序ConfigFileApplicationListener之后的自定义EnvironmentPostProcessor。

编辑:我最初的答案不起作用。 我要用这个代替它。



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

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

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