簡體   English   中英

java spring context:property-placeholder-設置占位符的屬性路徑

[英]java spring context:property-placeholder - set properties paths from placeholder

<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");
...

如何以第二種方式初始化我的應用程序? 在占位符中定義所有屬性文件的路徑。

您必須將其更改為:

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

從解析器來源獲取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無需進一步處理即可解析為a.properties,b.properties

因此,恐怕目前無法使用占位符。

可能有用的一件事是使用SpEL,如果它始終是系統屬性,則可以使用#{systemProperties['properties_location']}來解析該值。 那應該先解決。

您不能將屬性占位符用作占位符占位符解析器中的值。 就像說,“嘿,為所有屬性的位置解析占位符,然后就可以開始解析屬性了!”。

從邏輯上講,這只是有意義的。 我最近正在嘗試使用Spring屬性占位符解析,但偶然發現了這個問題。 我嘗試使用兩個屬性占位符配置器,一個用於解析第二個屬性的位置,第二個用於解析其余屬性。 當然,由於彈簧初始化其bean的方式,所以這很重要。

  1. 初始化bean后處理器
  2. 構造它們
  3. 構造所有其他bean

由於屬性占位符配置器是一個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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM