java - 根据配置文件在 Spring 中加载属性文件

标签 java spring

我有一个 Spring 3.1 应用程序。假设它有一个包含以下内容的 XML:

<context:property-placeholder location="classpath:somename.properties" />

<context:property-placeholder location="classpath:xxx.properties" />

我希望始终加载 some.properties(假设它存在),但第二个占位符的 xxx 部分将根据 Activity 配置文件替换为某个名称。我试过这个:

<beans profile="xx1">
    <context:property-placeholder location="classpath:xx1.properties" />
</beans>

<beans profile="xx2">
    <context:property-placeholder location="classpath:xx2.properties" />
</beans>

此外,这两个文件的属性具有相同的键但不同的值。

但它没有工作,因为一些后来的 bean 有一个属性的占位符,其键在 xx1.properties(和 xx2.properties)中定义,使 Spring 提示在应用程序上下文中找不到该键。

最佳答案

你可以这样做:

  <context:property-placeholder location="classpath:${spring.profiles.active}.properties" />

它工作正常,但在同时使用多个配置文件时可能无法适应。


当声明 2 个属性占位符时,如果第一个不包含所有应用程序键,则应将属性忽略 unresolvable = true,以便可以使用第二个占位符。 我不确定这是否是您想要做的,如果您希望 xx1 和 xx2 配置文件同时处于 Activity 状态,则可能会这样做。

请注意,像这样声明 2 个属性占位符会使它们独立,并且在 xx2.properties 的声明中,您不能重用 xx1.properties 的值。


如果您需要更高级的东西,您可以在应用程序启动时注册您的 PropertySources。

网络.xml

  <context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>com.xxx.core.spring.properties.PropertySourcesApplicationContextInitializer</param-value>
  </context-param>

您创建的文件:

public class PropertySourcesApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

  private static final Logger LOGGER = LoggerFactory.getLogger(PropertySourcesApplicationContextInitializer.class);

  @Override
  public void initialize(ConfigurableApplicationContext applicationContext) {
    LOGGER.info("Adding some additional property sources");
    String profile = System.getProperty("spring.profiles.active");
    // ... Add property sources according to selected spring profile 
    // (note there already are some property sources registered, system properties etc)
    applicationContext.getEnvironment().getPropertySources().addLast(myPropertySource);
  }

}

完成后,您只需在上下文中添加:

<context:property-placeholder/>

恕我直言,这是处理 spring 属性的最佳方式,因为您不再在所有地方声明本地属性,您可以通过编程控制正在发生的事情,并且可以在 xx2.properties 中使用属性源 xx1 值。


我们在工作中使用它并且效果很好。我们注册了 3 个额外的属性(property)来源: - 基础设施:由 Puppet 提供 - 配置文件:根据配置文件加载不同的属性。 - 通用:包含默认值,当所有配置文件共享相同的值等...

关于java - 根据配置文件在 Spring 中加载属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10669474/

相关文章:

java - 使用 Apache Tika 提取文本,然后在删除停用词后获取频繁出现的单词

java - 删除主键/id 引用的域实体时确保参照完整性

java - 如何将我的 spring xml 配置移到我的 web 应用程序之外?

java - J2EE Struts、Spring 和 Hibernate 框架问题

MySQL COMRESS DECOMPRESS 函数的 Java 模拟

Java:InvalidAlgorithmParameterException 质数大小必须是 64 的倍数

java - 简单的 JUnit 测试 assertTrue(true) 失败

java - 如果我们试图将 JSON 放入 hashmap 中,我们如何使用 jackson 处理 JSON 内部的 JSON?

java - Spring Boot - 是自动注入(inject)的单个实现类

java - 当我使用spring data保存实体时,Repository返回空指针异常