2011-02-23 73 views
3

在一個java應用程序中,我使用.properties文件來訪問應用程序相關的配置屬性。
例如,
AppConfig.properties這是說的內容,多個屬性文件

settings.user1.name=userone 
settings.user2.name=usertwo 
settings.user1.password=Passwrd1! 
settings.user2.password=Passwrd2! 

我通過Java文件accesing這些屬性 - AppConfiguration.java

private final Properties properties = new Properties(); 
    public AppConfiguration(){ 
     properties.load(Thread.currentThread().getContextClassLoader() 
       .getResourceAsStream("AppConfig.properties")); 
} 

現在,而不是保存在一個文件中的所有鍵值性質,我想將它們分成幾個文件(AppConfig1.properties,AppConfig2.properties,AppConfig3.properties等)。
我想知道是否有可能同時加載這些多個文件。

我的問題是不相似的 - Multiple .properties files in a Java project

謝謝。

回答

8

是的。只需要有多個加載語句。

properties.load(Thread.currentThread().getContextClassLoader() 
       .getResourceAsStream("AppConfig1.properties")); 
properties.load(Thread.currentThread().getContextClassLoader() 
       .getResourceAsStream("AppConfig2.properties")); 
properties.load(Thread.currentThread().getContextClassLoader() 
       .getResourceAsStream("AppConfig2.properties")); 

所有的鍵值對都可以使用使用屬性對象。

+0

哇,這麼簡單。我應該想到這一點。非常感謝你。我可以通過@duffymo去解決這個問題或解決方案 – 2011-02-24 08:45:20

+2

如果AppConfig1和AppConfig2中都存在「my.property」,屬性對象是否會包含第一個或第二個文件的值? – 2013-06-13 15:01:24

0

如果我理解你的問題,你心裏有兩個目標:

  1. 分區中的一個非常大的.properties文件分割成幾個較小的地方(鍵,值)對相關。
  2. 確保所有.properties文件同時可用,即使您使用線程同時讀取它們。

如果是這樣的話,我會用分割的.properties成多個文件出發,編寫處理的個人.properties文件的閱讀和所有的結果合併到一個Properties實例的合併一個新的類。

+0

這絕對正確。非常感謝。 – 2011-02-24 08:42:35

0

由於Properties對象實際上是地圖,您可以使用它們的所有方法,包括putAll(...)。在你的情況下,使用單獨的Properties對象加載每個Property文件,然後將它們合併到應用程序屬性中會很有用。

0

我對你有2個解決方案:

  • 你可以有不同的性質不同性質的目標文件
  • 可以使用putAll()合併。

    Properties properties1 = new Properties(); properties1.load(Thread.currentThread().getContextClassLoader() .getResourceAsStream("AppConfig1.properties")); Properties properties2 = new Properties(); properties.load(Thread.currentThread().getContextClassLoader() .getResourceAsStream("AppConfig2.properties")); Properties merged = new Properties(); merged.putAll(properties1); merged.putAll(properties2);