Java 根据活动配置文件从自定义文件加载属性

Java 根据活动配置文件从自定义文件加载属性,java,spring-boot,spring-profiles,spring-properties,Java,Spring Boot,Spring Profiles,Spring Properties,我有一个使用最新SpringBoot v.2.1.9的应用程序。该项目包含多个自定义文件,模式如下: file1-dev.properties file1-prod.properties file2-dev.properties 文件2-prod.properties等。 我想达到与Spring的应用程序{profile}.properties类似的行为,我的意思是从文件中加载与活动概要文件匹配的每个自定义道具。由于有大量属性,我无法将它们存储在application-{profile}.pro

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

file1-dev.properties file1-prod.properties file2-dev.properties 文件2-prod.properties等。 我想达到与Spring的应用程序{profile}.properties类似的行为,我的意思是从文件中加载与活动概要文件匹配的每个自定义道具。由于有大量属性,我无法将它们存储在application-{profile}.properties中,因为这会导致可读性问题

我希望找到一个严格的Java解决方案,而不需要Maven的任何变通方法,在构建之后物理地替换文件。 你能告诉我怎样才能达到这个目的吗

我目前的假设是重写ApplicationContextInitializer中的initialize方法,然后检查配置文件并执行逻辑来选择文件,但是我不确定这是否是最有效的方法

非常感谢你的帮助

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

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

1实现EnvironmentPostProcessor并重写postProcessEnvironment方法

2从参考资料->获取文件我使用了org.springframework.core.io.support包中的PathMatchingResourcePatternResolver类。一旦传递了ClassLoader实例,就可以执行getResourcesString路径方法

3迭代资源[]数组并选择满足您需求的人

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

如果文件名与模式匹配,您可以只筛选这些文件。