获取配置属性
在系统中,由于有些属性不是固定的,比如数据库用户名与密码,所以需要相应的配置文件。而 配置文件有两件方式,一种是属性properties文件,一种是XML文件。 读取属性文件的方式在较早的配置文件中比较流行:
Properties bundle = new Properties();
bundle.load(getClass().getResourceAsStream("messages.properties"))
assertThat(bundle.getProperty("first.name"), is("Arthur"));
assertThat(bundle.getProperty("last.name"), is("Dent"));
assertThat(bundle.getProperty("favorite.object"), is("Tsowel"));
其中加载属性的类也可以使用ClassLoader:
.........
ClassLoader classLoader = getClass().getClassLoader();
bundle.load(classLoader.getResourceAsStream("messages.properties"));
......
.
属性文件messages.properties内容如下:
first.name = Arthur last.name = Dent favorite.object = Towel
两种方式有些区别,先说Class的加载方式,默认为Class所在的路径,如果在包com下,则是相对于com目录的配置文件,如果在文件名前加"/",则表示相对于src目录下的路径。至于ClassLoader默认为根目录,即src下的路径。如果用new File()创建的文件,则默认为工程目录下的路径。
由于properties对中文的支持不完善,所以现在更流行通过XML的方式来配置属性,加载XML的方式也同样简单:
....
Properties bundle = new Properties();
bundle.loadFromXML(new FileInputStream(new File("messages.xml")));
...
上面说过了,这XML文件相对的是工程目录的路径。但是XML文件必须遵循相应的文件格式,messages.xml内容如下:
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>user simple properties</comment>
<entry key="first.name"><![cdata[arthur]]></entry>
<entry key="last.name"><![cdata[dent]]></entry>
<entry key="favorite.object"><![cdata[towel]]></entry>
</properties>