Java 如何使代码中的另一个对象可以访问对象?
在java中,我从属性文件读取到属性对象:Java 如何使代码中的另一个对象可以访问对象?,java,Java,在java中,我从属性文件读取到属性对象: static Properties fileProp = null; // holds file properties public static void main( final String[] args ) throws IOException { ... //load a properties file InputStream is = LearnButtonPressHttpHandler.class
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
}
稍后,深入代码,再深入几层,我需要访问这个properties对象,但发现我没有访问这个fileProp对象的权限。我不想把这个对象作为参数传递到我需要它的地方。这将解决问题,但似乎不是一个优雅的解决方案。有更好的方法吗?为
fileProp
引用创建一个static
getter:
public static Properties getFileProp()
{
return fileProp;
}
这样,任何其他需要它的代码都可以访问它。这是依赖项注入的主要功能之一。例如,在Spring中有一个PropertyPlaceHolderConfigure,用于在构建bean时将属性从一个位置注入bean中(参见四人一组)
许多框架只做静态属性管理,例如Play。然后您基本上实现了一个。普通Java中最简单的方法是使用
单例模式,在应用程序启动时单例加载属性,或者在该类中有一个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);
}
}
这是一个独立的应用程序,还是在应用程序服务器或框架的某个上下文中运行?目前,它是独立的。这似乎很相关:这真的很有帮助!谢谢其他答案也可能有效,但这是一个对我有效的答案!随时都可以。其他一些答案在可维护性和设计的编码风格方面是好的。我的解决方案快速简单,适合小项目。