java spring context:property-placeholder - 设置来自占位符的属性路径

时间:2014-06-04 13:16:12

标签: java spring properties

<context:property-placeholder
    location="a.properties,b.properties"
    ignore-unresolvable="true"/>

结果:两个属性文件都已加载

<context:property-placeholder
    location="${properties_location}"
    ignore-unresolvable="true"/>

其中properties_location是“a.properties,b.properties”

result: Exception in thread "main" org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [a.properties,b.properties] cannot be opened because it does not exist

编辑:${properties_location}按以下方式设置:

System.getProperties().setProperty("properties_location", "a.properties,b.properties");
ApplicationContext ctx = new GenericXmlApplicationContext("context.xml");
...

如何以第二种方式初始化我的应用程序?在占位符中定义所有属性文件的路径。

3 个答案:

答案 0 :(得分:1)

您必须将其更改为:

<context:property-placeholder
location="classpath:a.properties,
          classpath:b.properties"
ignore-unresolvable="true"/>

答案 1 :(得分:1)

property-placeholder元素的解析器源。

String location = element.getAttribute("location");
if (StringUtils.hasLength(location)) {
    String[] locations = StringUtils.commaDelimitedListToStringArray(location);
    builder.addPropertyValue("locations", locations);
}

首先检索位置,如果有值,则转换为String[]。 Springs转换服务负责替换String[]中的任何占位符。但在那一刻,properties_location占位符只是数组中的一个元素,无需进一步处理即可解析为a.properties,b.properties

所以目前我不敢用占位符来实现这一点。

可能有用的一件事是使用SpEL,如果它始终是一个系统属性,您可以使用#{systemProperties['properties_location']}来解析该值。这应该先解决。

答案 2 :(得分:0)

您无法将属性占位符用作占位符占位符解析程序中的值。它就像是说,“嘿,解决占位符所有属性的位置,然后你就可以开始解析属性!”。

逻辑上它只是有意义。我最近正在尝试弹簧属性占位符解决方案,并偶然发现了同样的问题。我尝试使用两个属性占位符配置器,一个用于解析第二个属性的位置,第二个用于解析其余属性。当然,由于弹簧初始化豆子的方式,这种剂量起作用。

  1. 初始化bean后处理器
  2. 构建它们
  3. 构建所有其他bean
  4. 由于属性占位符配置器是一个bean后处理器,如果你有多个它们,它们会同时进行初始化和构建,所以在构造时不知道每个其他属性

    修改

    鉴于属性位置是系统属性,您可以:

    System.getProperties().setProperty("properties_location_a", "classpath:/a.properties");
    System.getProperties().setProperty("properties_location_b", "classpath:/b.properties");
    

    然后在你的spring content.xml中:

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="ignoreUnresolvablePlaceholders" value="true"/>
      <property name="locations">
        <list>
          <value>${properties_location_a}</value>
          <value>${properties_location_b}</value>
        </list>
      </property>
    </bean>
    
相关问题