本文内容演示属性文件用法的简单例子。
首先定义模型接口Model,视图接口View,以及它们实现类ImpModel,ImpView.
Model中定义方法getString();View中定义Model实例为其属性,在实现类ImpView中实现方法
disPlay(),其方法体为Model实例的getString()方法,并将其打印出来。
定义属性文件
msf.properties
disPalyer.class
=
ImpView
provider.class
=
ImpModel
编写工厂类
TestFactory.java
import
java.util.Properties;
public
class
TestFactory{
private
static
TestFactory instance
=
null
;
private
Properties props
=
null
;
private
View disPalyer
=
null
;
private
Model provider
=
null
;
static
{
instance
=
new
TestFactory();
}
public
static
TestFactory getInstance() {
return
instance;
}
public
View getView() {
return
disPalyer;
}
public
Model getModel() {
return
provider;
}
private
TestFactory() {
props
=
new
Properties();
try
{
//
加载属性文件
props.load( TestFactory.
class
.getResource(
"
msf.properties
"
).openStream());
//
获取属性值
String rendererClass
=
props.getProperty(
"
renderer.class
"
);
String providerClass
=
props.getProperty(
"
provider.class
"
);
//
产生类实例对象
renderer
=
(View) Class.forName(rendererClass).newInstance();
provider
=
(Model) Class.forName(providerClass).newInstance();
}
catch
(Exception ex) {
ex.printStackTrace();
}
}
}
最后编写测试方法
1 public static void main(String[] args) {
2 View mr = TestFactory.getInstance().getView();
3 Model mp = TestFactory.getInstance().getModel();
4 mr.setModel(mp);
5 mr.disPlay();
6 }
综上,对属性文件的加载主要语句
props.load( TestFactory.class.getResource("msf.properties").openStream());
并分别通过newInstance()产生实例对象,本例中使用了设计模式中的工厂模式以及单例实例模式,
因此具有对设计模式进一步了解的意义。
注:另一用法
1 public static void main(String[] args) throws Exception {
2
3 // get the bean factory
4 BeanFactory factory = getBeanFactory();
5
6 View mr = (View) factory.getBean("view");
7 mr.render();
8 }
9
10 private static BeanFactory getBeanFactory() throws Exception {
11 // get the bean factory
12 DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
13
14 // create a definition reader
15 PropertiesBeanDefinitionReader rdr = new PropertiesBeanDefinitionReader(
16 factory);
17
18 // load the configuration options
19 Properties props = new Properties();
20 props.load(TestFactory.class.getResource("msf.properties").openStream());
21
22 rdr.registerBeanDefinitions(props);
23
24 return factory;
25 }
凤凰涅槃/浴火重生/马不停蹄/只争朝夕
隐姓埋名/低调华丽/简单生活/完美人生