我想用屬性文件中的公共靜態最終字段創建Constants類。 問題是ClassLoader始終爲空,我無法獲得屬性文件InputStream。屬性文件中的Spring和Constants類
我使用的是Spring Java Configuration,我知道@PropertySource和@Value spring註解,但我認爲舊式的Constants類在代碼中更具可讀性。
@Autowired
Constants constants;//in every class that needs constant
//...
constants.getArticleLimit()
VS簡單
Constants.ARTICLES_LIMIT //static var version
這裏是我的代碼:
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,如果我正確理解這將迫使我在每個使用它們的類中添加所有常量。 –