1.通过java.util.Properties.Properties类读取配置信息
Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。加载属性文件,它提供了两个方法:load和loadFromXML
load有两个方法的重载:load(InputStream inStream)、load(Reader reader),所以,可根据不同的方式来加载属性文件。可根据不同的方式来获取InputStream。
public Properties propertiesTest() {
Properties props = null;
InputStream is = null;
try {
// 1.通过当前类加载器的getResourceAsStream方法获取 // is = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.properties");
// 2、从文件获取 //is = new FileInputStream(new File(this.getClass().getResource("/test.properties").getPath()));
// 3、也是通过类加载器来获取,和第一种一样 // is = ClassLoader.getSystemResourceAsStream("test.properties");
// 4.在servlet中,还可以通过context来获取InputStream // is = context.getResourceAsStream("filePath");
// 5.通过URL来获取 URL url = Thread.currentThread().getContextClassLoader().getResource("test.properties");
is = url.openStream();
if (is == null) {
throw new FileNotFoundException("" + "file is not found");
}
props = new Properties();
props.load(is);
Iterator it=props.stringPropertyNames().iterator();
while(it.hasNext()){
String key=it.next();
System.out.println(key+":"+props.getProperty(key));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return props;
}
2.通过ResourceBundle类读取配置信息
这个类主要用来解决国际化和本地化问题。这个类的作用就是读取资源属性文件(properties),然后根据.properties文件的名称信息(本地化信息),匹配当前系统的国别语言信息(也可以程序指定),然后获取相应的properties文件的内容。
使用这个类,要注意的一点是,这个properties文件的名字是有规范的:一般的命名规范是: 自定义名语言代码国别代码.properties,
如果是默认的,直接写为:自定义名.properties
比如:
test_en_US.properties
test_zh_CN.properties
test.properties
如果是CN环境,使用ResourceBundle类,读取的是test_zh_CN.properties和test.properties和并集。如果两个配置文件都有一个属性,test_zh_CN.properties中的属性会覆盖test.properties配置文件中的属性。
缺点:只能加载类classes下面的资源文件,且只能读取.properties文件。
public void resourceBundleTets(){
ResourceBundle resourceBundle = ResourceBundle.getBundle("test");
// 通过资源包拿到所有的key Enumeration allKey = resourceBundle.getKeys();
while (allKey.hasMoreElements()) {
String key = allKey.nextElement();
String value = resourceBundle.getString(key);
System.out.println(key+":"+value);
}
}
3.使用Spring提供的PropertiesLoaderUtils加载配置文件
Spring 提供的 PropertiesLoaderUtils 允许您直接通过基于类路径的文件地址加载属性资源。 最大的好处就是:实时加载配置文件,修改后立即生效,不必重启。
public void testPropertiesLoaderUtils() throws IOException {
Properties properties = PropertiesLoaderUtils.loadAllProperties("test.properties");
for(Object key:properties.keySet()){
System.out.print(key+":");
System.out.println(properties.get(key));
}
}
4.使用@value注解的方式获取properties文件中的配置值
1、在applicationContext.xml文件中配置properties文件
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
classpath:app.properties
2、在bean中使用@value注解获取配置文件的值
@Value("${chengmi_crawl_timer_enable}")
private Boolean timerEnabled;
即使给变量赋了初值也会以配置文件的值为准。
源码链接github.com