我想创建带有公共(public)静态最终字段的常量类,我从属性文件中获取这些字段。 问题是 ClassLoader 始终为 null,我无法获取属性文件 InputStream。
我正在使用 Spring Java Configuration 并且我知道 @PropertySource 和 @Value spring 注释,但我认为旧式常量类在代码中更具可读性。
@Autowired
Constants constants;//in every class that needs constant
//...
constants.getArticleLimit()
与简单
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;
}
}
最佳答案
经过一些测试,这是问题所在:
System.out.println(Constants.class.getClass());
这会打印 java.lang.Class
,它可能还没有被类加载器加载。这是因为 SomeClass.class
的类是 java.lang.class
。
删除 getClass()
并且 Classloader 不会为 null。不需要 clazz
变量。这应该是您需要做的所有事情:
ClassLoader cl = Constants.class.getClassLoader();
关于java - 属性文件中的 Spring 和常量类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42768629/