2016-05-03 26 views
1

我有一個場景,我試圖在我的應用程序中實現錯誤代碼機制。這是我目前遵循的方法。如何加載屬性文件一次並在整個應用程序中使用它在java中

Properties prop = new Properties(); 
      InputStream input = null; 

      try { 

       String filename = "ErrorCode.properties"; 
       input = getClass().getClassLoader().getResourceAsStream(filename); 
       if (input == null) { 
        log.debug("Sorry, unable to find " + filename); 
        return null; 
       } 

       prop.load(input); 

       Enumeration<?> e = prop.propertyNames(); 
       while (e.hasMoreElements()) { 
        String key = (String) e.nextElement(); 
        String value = prop.getProperty(key); 
        log.debug("Key : " + key + ", Value : " + value); 

       } 

但我需要很多不同的類中的錯誤代碼,我不想一直在不同的類中編寫上面的代碼。

是否有任何其他方式初始化屬性文件一次,並在類中的任何地方使用它。

我該如何做到這一點?

實現此目的有哪些不同的可能方法?

我使用的是春天,有什麼辦法可以在春天實現這個嗎?

我打開任何其他機制,而不是屬性文件。

+0

如果是錯誤代碼,您可能需要進行本地化 - 在這種情況下,請查看以下解決方案:http://stackoverflow.com/questions/6246381/getting-localized-message-from-resourcebundle-via-annotations-在 - 彈簧 - framewor – Jan

回答

0

爲什麼不只是實現一個單獨的singleton類,就像「ErrorCodes」,在創建對象時初始化屬性文件一次,然後通過getter檢索文件?

0

定義一個Constants.java並添加要在整個應用程序運行時使用的屬性。這些屬性可以被其他類使用,並且不需要爲每個類定義進行初始化。

public class Constants { 
public static String[] tableAndColumnNames; 
public static String[] getTableAndColumnNames() { 
     return tableAndColumnNames; 
    } 
    public static void setTableAndColumnNames(String tableNames) { 
     Constants.tableAndColumnNames = tableNames.split(";"); 
    } 

public static String getDB() { 
     return DB; 
    } 
public static final String HSQLBD = "HSQLDB"; 
    public static final String ORACLE = "ORACLE"; 
public static String DB; 
    public static void setDB(int dB) { 
     if (dB == 0) { 
      Constants.DB = HSQLBD; 
     } else { 
      Constants.DB = ORACLE; 
     } 
    } 
} 

在應用程序啓動時加載這些屬性。當您正在加載的屬性只是做一組常量像下面

public static void loadProperties() { 
Properties property = new Properties(); 
      InputStream input = CommonUtilities.class.getResourceAsStream("/DB.properties"); 
      property.load(input); 
      Constants.setDB(Integer.parseInt(prop.getProperty("DB"))); 
Constants.setTableAndColumnNames(property.getProperty("tableAndColumnNames")); 
} 

而且性能已經initializedd你可以在程序的任何位置使用它後僅參照恆類。像

public void someOtherClass() 

public static void main(String[] args) { 
    if(this.DB.equals(Constans.getDB()) // will return the DB from the properties class 
    // no need to initialize properties again in every class. 
} 

希望這會有所幫助。

相關問題