プロパティファイルから取得するpublic static finalフィールドを持つConstantsクラスを作成します。 問題は、ClassLoaderは常にnullです。プロパティファイルInputStreamを取得できません。プロパティファイルのSpringとConstantsクラス
私は春のJavaの設定を使用していると私は@PropertySourceと@value春の注釈について知っているが、私はコード内の古いスタイルの定数クラスより読みやすいと思います。シンプル
Constants.ARTICLES_LIMIT //static var version
対
@Autowired
Constants constants;//in every class that needs constant
//...
constants.getArticleLimit()
ここに私のコードです:テストのビットの後
package org.simpletest.utils
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Constants {
private static final Logger LOG = Logger.getLogger(Constants.class);
public static final int ARTICLES_LIMIT;
public static final String PROPERTIES_LOCATION = "constants.properties";
static {
Properties p = new Properties();
//default values
int articlesLimit = 10;
Class<?> clazz = Constants.class.getClass();
ClassLoader cl = clazz.getClassLoader();
//try to load from properties file
try(final InputStream is = cl.getResourceAsStream(PROPERTIES_LOCATION)){
p.load(is);
articlesLimit= Integer.parseInt(p.getProperty("articleslimit"));
} catch (IOException e) {
LOG.debug(String.format("Unable to load {0} properties file. Getting constants by default values.",PROPERTIES_LOCATION),e);
}
ARTICLES_LIMIT = articlesLimit;
}
}
なぜプロパティファイルから@Environmentを読み込まないのですか? –
PropertyPlaceholderをコンテキストで使用する場合は、Spring Beanで直接プロパティ値を使用できます。私は正しく、これはそれらを使用するすべてのクラスのすべての定数を追加するために私を強制的に理解していれば、http://stackoverflow.com/questions/9259819/how-to-read-values-from-properties-file –
@MichaelPeacockを参照してください。 –