2013-01-22 34 views
0

如何從ResourceBundle切換到屬性(類)?如何從ResourceBundle切換到屬性(類)?

我有一個應用程序分裂成2個Java項目(核心&網絡)。核心模塊中的Java服務必須從位於Web模塊中的.properties文件中讀取值。 當我使用ResourceBundle時,它按預期工作。

我想切換到Properties類有幾個原因(特別是因爲ResourceBundle被緩存,我不想實現ResourceBundle.Control沒有緩存)。 不幸的是我不能讓它工作,特別是因爲我無法找出使用哪個正確的相對路徑。

我讀了反編譯的ResourceBundle類(等),並注意到某些ClassLoader上使用了getResource()。 因此,不是直接使用FileInputStream,而是使用getResource()或簡單的getResourceAsStream()對ServiceImpl.class或ResourceBundle.class進行測試,但仍然沒有成功...

任何人有想法如何獲得此工作?謝謝!

這是我與服務應用的核心獲得的屬性值:

app-core 
    src/main/java 
     com.my.company.impl.ServiceImpl 

      public void someRun() { 
       String myProperty = null; 
       myProperty = getPropertyRB("foo.bar.key"); // I get what I want 
       myProperty = getPropertyP("foo.bar.key"); // not here... 
      } 

      private String getPropertyRB(String key) { 
       ResourceBundle bundle = ResourceBundle.getBundle("properties/app-info"); 
       String property = null; 
       try { 
        property = bundle.getString(key); 
       } catch (MissingResourceException mre) { 
        // ... 
       } 
       return property; 
      } 

      private String getPropertyP(String key) { 
       Properties properties = new Properties(); 

       InputStream inputStream = new FileInputStream("properties/app-info.properties"); // Seems like the path isn't the good one 
       properties.load(inputStream); 
       // ... didn't include all the try/catch stuff 

       return properties.getProperty(key); 
      } 

這是網絡模塊,其中駐留的屬性文件:

app-web 
    src/main/resources 
     /properties 
      app-info.properties 
+0

相關:http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream/2308388#2308388 – BalusC

回答

2

您應該使用getResource()getResourceAsStream()適當路徑和類加載器。

InputStream inputStream = getClass()。getClassLoader()。getResourceAsStream(「properties/app-info.properties」);

確保文件被命名爲app-info.properties,而不是像app-info_en.properties這將由ResourceBundle發現(上下文匹配時),但不是由getResourceAsStream()

2

你不應該試圖從文件系統讀取屬性。改變你的方法,獲取屬性來從資源流中加載它們。僞代碼:

private String getPropertyP(final String key) { 
    final Properties properties = new Properties(); 

    final InputStream inputStream = Thread.currentThread().getContextClassLoader() 
     .getResourceAsStream("properties/app-info.properties"); 
    properties.load(inputStream); 

    return properties.getProperty(key); 
} 
+0

此解決方案太(測試過),但我更喜歡另一種是整潔給我和沒有線程的東西。 – maxxyme