【问题标题】:Add applicationConfig PropertySource to new Environments将 applicationConfig PropertySource 添加到新环境
【发布时间】:2023-03-31 02:18:02
【问题描述】:

我目前正在将现有应用程序迁移到 Spring Boot 1.2(使用 Mule 3;与 Spring 4.2 不兼容)。这个应用程序包含一个库提供的(我无法修改)servlet,它通过读取一些包含 bean 定义的应用程序包含的 XML 文件来创建多个 ClasspathXmlApplicationContexts 来执行 Mule 引导过程。

我的问题是这个 XML 文件包含几个占位符,应该根据活动配置文件以不同方式解析(我已经将这些变量存储在 application.yml 文件中,具有不同的配置文件),但 applicationConfig PropertySource 不是在由新应用程序上下文创建的 StandardEnvironments 上可用。

我可以将 YML 文件转换为 .properties 文件并在每个 XML 文件中创建一个新的 PropertyPlaceholderConfigurer,指向同一个应用程序-#{systemProperties['spring.profiles.active']}.properties,但是:

  1. 我会失去 Boot 使用约定和优先级将 .properties 文件定位在不同内部/外部位置的灵活性,这对于要在不同环境中迁移的应用程序来说听起来很方便。

  2. 如果我需要多次添加相同的定义,我想有一种我忽略的编程方式。

有人知道如何将 applicationConfig PropertySource 的内容添加到所有新创建的 ApplicationContexts 中,而无需修改创建它们的类吗? Spring Boot 1.2 没有 EnvironmentPostProcessor 的强大功能。

【问题讨论】:

    标签: java spring spring-boot spring-environment


    【解决方案1】:

    当你创建一个新的上下文时,所有来自主环境的属性源都可以使用类似的东西添加到新创建的上下文中。

    public AnnotationConfigApplicationContext createNewApplicationContext(ConfigurableEnvironment mainEnv) throws IOException {
    AnnotationConfigApplicationContext newContext = new AnnotationConfigApplicationContext();
    //Add scan for your packages
    newContext.scan("com.abc.mycompany");
    //Also Any different profile in association with new context can be added newContext.getEnvironment().addActiveProfile("newProfile");
    mainEnv.getPropertySources().stream().filter(propertySource -> propertySource.getName().startsWith("applicationConfig")).forEach(newContext.getEnvironment().getPropertySources()::addLast);
    newContext.refresh();
    return newContext;
    }
    

    现在您可以创建任意数量的上下文。同样要在所有 bean 创建结束时处理此问题,您可以 @PostConstruct 并编写一个调用此新上下文生成函数的包装器方法。

    【讨论】:

      【解决方案2】:

      供将来参考:我通过实现一个 ApplicationListener 解决了这个问题,它在所有 PropertySources 中搜索 applicationConfig 的属性,并将其所有属性放在 System.getProperties() 映射中,所有 ApplicationContexts 都可以通过设置在 XML 文件上为空。

      【讨论】:

        猜你喜欢
        • 2021-11-03
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-10
        • 2019-12-17
        • 2021-07-09
        相关资源
        最近更新 更多