Spring笔记之三(Usage of property config)

转贴处 http://www.blogjava.net/improviser/archive/2007/09/24/147777.html

本文内容演示属性文件用法的简单例子。
首先定义模型接口Model,视图接口View,以及它们实现类ImpModel,ImpView.
Model中定义方法getString();View中定义Model实例为其属性,在实现类ImpView中实现方法
disPlay(),其方法体为Model实例的getString()方法,并将其打印出来。

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> 定义属性文件
msf.properties
disPalyer.class
=ImpView
provider.class
=ImpModel


编写工厂类
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> TestFactory.java
import java.util.Properties;
public class TestFactory{
private static TestFactoryinstance = null ;
private Propertiesprops = null ;
private ViewdisPalyer = null ;
private Modelprovider = null ;

static {
instance
= new TestFactory();
}

public static TestFactorygetInstance(){
return instance;
}

public ViewgetView(){
return disPalyer;
}

public ModelgetModel(){
return provider;
}

private TestFactory(){
props
= new Properties();

try {
// 加载属性文件
props.load(TestFactory. class .getResource( " msf.properties " ).openStream());

// 获取属性值
StringrendererClass = props.getProperty( " renderer.class " );
StringproviderClass
= props.getProperty( " provider.class " );

// 产生类实例对象
renderer = (View)Class.forName(rendererClass).newInstance();
provider
= (Model)Class.forName(providerClass).newInstance();
}
catch (Exceptionex){
ex.printStackTrace();
}
}
}


最后编写测试方法
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> 1 public static void main(String[]args){
2 Viewmr = TestFactory.getInstance().getView();
3 Modelmp = TestFactory.getInstance().getModel();
4 mr.setModel(mp);
5 mr.disPlay();
6 }

综上,对属性文件的加载主要语句
props.load( TestFactory.class.getResource("msf.properties").openStream());
并分别通过newInstance()产生实例对象,本例中使用了设计模式中的工厂模式以及单例实例模式,
因此具有对设计模式进一步了解的意义。

注:另一用法
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> 1 public static void main(String[]args) throws Exception{
2
3 // getthebeanfactory
4 BeanFactoryfactory = getBeanFactory();
5
6 Viewmr = (View)factory.getBean( " view " );
7 mr.render();
8 }
9
10 private static BeanFactorygetBeanFactory() throws Exception{
11 // getthebeanfactory
12 DefaultListableBeanFactoryfactory = new DefaultListableBeanFactory();
13
14 // createadefinitionreader
15 PropertiesBeanDefinitionReaderrdr = new PropertiesBeanDefinitionReader(
16 factory);
17
18 // loadtheconfigurationoptions
19 Propertiesprops = new Properties();
20 props.load(TestFactory. class .getResource( " msf.properties " ).openStream());
21
22 rdr.registerBeanDefinitions(props);
23
24 return factory;
25 }


你可能感兴趣的:(property)