2016-05-03 9 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-春のフレームワーク – Jan

答えて

0

"ErrorCodes"のような別のシングルトンクラスを実装してオブジェクト作成時にプロパティファイルを一度初期化してからゲッターでファイルを取得するのはなぜですか?

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. 
} 

希望します。

関連する問題