1

我有一个带有最新 SpringBoot v.2.1.9 的应用程序。该项目包含多个自定义文件,其模式如下:

  • file1-dev.properties
  • file1-prod.properties
  • file2-dev.properties
  • file2-prod.properties 等

我想达到与 Spring 的 application-{profile}.properties 类似的行为,我的意思是从文件中加载每个自定义道具,这些道具与活动配置文件相匹配。由于大量属性,我无法将它们存储在 application-{profile}.properties 中,因为它会导致可读性问题。

我想找到一个严格的 Java 解决方案,没有任何 Maven 的解决方法,在构建后物理替换文件。你能告诉我我怎样才能达到这种方法吗?

我目前的假设是覆盖 ApplicationContextInitializer 的初始化方法,然后检查配置文件并执行逻辑以选择文件,但是我不确定这是否是最有效的方法。

非常感谢您的帮助。

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    String profile = System.getProperty("spring.profiles.active");
    //selecting files according to active profile
    applicationContext.getEnvironment().getPropertySources().addLast(prop);
}
4

1 回答 1

1

我已经解决了我的问题。如果有人会遇到同样的麻烦,请在下面找到我的解决方案:

1) 实现 EnvironmentPostProcessor 并覆盖 postProcessEnvironment 方法。

2) 从资源中获取文件-> 我使用了 org.springframework.core.io.support 包中的 PathMatchingResourcePatternResolver 类。一旦我们传递了 ClassLoader 实例,我们就可以执行 getResources(String path) 方法。

3)遍历 Resource[] 数组并选择满足您需求的那些

4) 创建一个 PropertiesPropertySourceLoader 实例并从资源路径加载属性。

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    Resource[] resources = getResources("classpath*:/properties/*.*");
    List<List<PropertySource<?>>> propertySources = getPropertySources(resources);
    for (int i = 0; i < propertySources.size(); i++) {
        propertySources.get(i).forEach(propertySource -> environment.getPropertySources().addLast(propertySource));
    }
    application.setEnvironment(environment);
}

private Resource[] getResources(String path) {
    ClassLoader classLoader = this.getClass().getClassLoader();
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(classLoader);
    try {
        return resolver.getResources(path);
    } catch (IOException ex) {
        throw new IllegalStateException("Failed to load props configuration " + ex);
    }
}
于 2019-10-14T10:24:11.117 回答