在java中,我正在从属性文件读取到Properties对象中:
static Properties fileProp = null; // holds file properties
public static void main( final String[] args ) throws IOException
{
...
//load a properties file
InputStream is = LearnButtonPressHttpHandler.class.getResourceAsStream("/rsrc/file.properties");
fileProp.load(is);
...
// more objects are created
}
稍后,在代码的更深层次,我需要访问这个属性对象,但发现我没有访问这个fileProp对象的权限。我不想把这个对象作为参数传递到我需要的地方。它可以解决问题,但似乎不是一个很好的解决方案。有更好的方法吗?
为fileProp
引用创建一个static
getter:
public static Properties getFileProp()
{
return fileProp;
}
这样,任何其他需要它的代码都可以访问它。
普通Java中最简单的方法是使用Singleton
模式,在应用程序启动时加载您的属性singleton,或者在该类中有一个getProperties
方法,如果属性已加载,则返回属性,如果未加载,则加载属性。
例如:
public class MySingleton {
private static MySingleton instance = null;
protected MySingleton() {
// Exists only to defeat instantiation.
}
public static MySingleton getInstance() {
if(instance == null) {
instance = new MySingleton();
instance.loadData()
}
return instance;
}
private void loadData(){
//doSomething
}
}
在这种情况下,您可以调用MySingleton.getInstance()
,这将为您获得所需的数据对象,而不重新加载以前加载的数据对象。如果是第一次,它会懒散地加载。
如果您使用的是框架或应用程序服务器,则有多种方法,具体取决于您的堆栈提供了什么。例如,在Spring
中,singleton是默认的bean类型。
创建执行属性加载的Singleton类(我更喜欢Singleton而不是静态类)。然后,您可以从任何位置访问属性。
public class Singleton {
private static Singleton INSTANCE = null;
Properties props = new Properties();
public static final Singleton getInstance() throws IOException {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
INSTANCE.loadProperties();
}
}
}
return INSTANCE;
}
private void loadProperties() throws IOException{
InputStream is = Singleton.class.getResourceAsStream("/rsrc/file.properties");
props.load(is);
}
public Object getData(String key){
return props.get(key);
}
}
这是依赖注入所做的主要工作之一。例如,在Spring中有一个PropertyPlaceholderConfigurer,用于在构建bean时将属性从一个位置注入到bean中(参见GangofFour中的原型模式)。
许多框架只是做静态属性管理,例如Play。那么你基本上就是在实现Singleton。