java - 从 java config 加载额外的 spring 配置文件

标签 java spring spring-boot

是否有可能从 java 配置加载额外的 spring 配置文件?

我知道我可以使用 -Dspring.profile.active 参数并将配置文件添加到 application.properties 中的 spring.profiles.include

我需要的是能够从 java 配置激活配置文件。我创建了 PropertyPlaceholderConfigurer,我在其中添加了一些自定义属性文件,其中还包含属性 spring.profiles.include,所有属性都已加载并且工作正常,但 spring 不会激活任何配置文件使用此属性包含哪些内容。

@Bean
public static PropertyPlaceholderConfigurer ppc() throws IOException {
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    ppc.setLocations(new ClassPathResource("properties/" + property + ".properties"));
    ppc.setIgnoreUnresolvablePlaceholders(true);
    return ppc;
}

最佳答案

Activity Spring 配置文件通过以下配置在属性中定义:spring.profiles.active:

您应该在导入的所有文件中列出它们通过上述配置 key 激活的配置文件。

编辑

首先,根据 official documentation配置spring.profiles.include更适合无条件添加 Activity 配置文件。

其次,我可以假设 PropertyPlaceholderConfigurer 不适合您想要实现的目标。官方文档列出了您可以使用的方法 Externalize Configuration .你可以尝试使用@PropertySource:

@PropertySources({
        @PropertySource(value = "classpath:application.properties"),
        @PropertySource(value = "classpath:other.properties", ignoreResourceNotFound = true)
})
public class Application {
       ...
    }
}

此外,您可以尝试在 application.properties 内的属性 spring.config.location 中列出其他属性文件,如所述 here .

关于java - 从 java config 加载额外的 spring 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43203205/

相关文章:

java - Spring data solr HttpSolrClient 不使用来自实体的核心注释

java - 在Spring boot中创建外键-H2数据库

java - 如何对始终 Autowiring 的接口(interface)进行单元测试 (Java)

java - 在数据库中读取/写入 POJO 作为 JSON 字符串

java - Spring Data REST 存储库中的枚举翻译

java - 在一个 Controller 中使用多个 Spring JpaTransactionManager?

Java If 语句

java - Mockito 监视 HSQLDB 连接

java - 理解发生在关系之前

java - 访问用户上的 LAZY 集合时出现 LazyInitializationException