1.Maven的pom文件引入:
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.10</version>
</dependency>
2.文件的加载
PropertiesConfiguration config=new PropertiesConfiguration("test.properties");
说明:PropertiesConfiguration 会自动到以下目录去搜索文件:a.当前目录 b.用户主目录 c.classpath下
工具类一般写法:
package com.gp.commons.configuration;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.lang.StringUtils;
public class PropertyUtil {
private static final String DEFAULT_PROPERTY = "conf/conf";
private static final String PROPERTY_SUFIX = ".properties";
private static final Map<String,PropertiesConfiguration> CONFIGURATIONS
=new HashMap<String, PropertiesConfiguration>();
private static PropertiesConfiguration getInstance(String filename){
filename=getPropertyName(filename);
PropertiesConfiguration config=CONFIGURATIONS.get(filename);
try {
if(config==null){
config=new PropertiesConfiguration(filename);
config.setReloadingStrategy(new FileChangedReloadingStrategy());
CONFIGURATIONS.put(filename, config);
}
} catch (ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException("cannot find property file for : " + filename);
}
return config;
}
private static String getPropertyName(String name)
{
if (StringUtils.isBlank(name))
{
name = DEFAULT_PROPERTY;
}
return name.endsWith(PROPERTY_SUFIX) ? name : (name += PROPERTY_SUFIX);
}
public static String getString(String key, String propertyInstance)
{
return getInstance(propertyInstance).getString(key);
}
public static void main(String[] args) {
PropertyUtil test = new PropertyUtil();
System.out.println(test.getString("colors.background","configtest"));
System.out.println(test.getString("username","configtest"));
}
}
3.include 包含文件
如果property文件里有叫做 "include
"的键值对,并且值是一个 property文件名, 这么个文件也将被自动包含进配置信息中
configtest.properties文件如下:
colors.background = #FFFFFF
include=configtestchild.properties
4.自动重新加载
通常你需要开启一个线程来监视配置文件的时间,并在文件被修改后重新加载进来。 CommonsConfiguration集成了这个加载机制,只需要设置
config.setReloadingStrategy(new FileChangedReloadingStrategy());
如果修改了properties的值,配置信息都能够自动刷新,修改后的值立即在程序里生效
5.可以保存properties文件
PropertiesConfiguration config=new PropertiesConfiguration("test.properties");
cofig.setProperty("username", "三个");
cofig.save();
//cofig.save("newBak.properties"); 可以另存为一个新的文件
调用save()方法就可以保存你的配置
如果开启了:cofig.setAutoSave(true); 会在调用cofig.setProperty("username", "三个"); 后自动对文件进行保存.
6.list arrays
CommonsConfiguration可以返回一组值 各个值之间用,号隔开
如:test.list=java,c++,oracle
String[] array=cofig.getStringArray("test.list");
//System.out.println(array);
List<Object> list=cofig.getList("test.list");
list.stream().map(a->a.toString()).forEach(System.out::println);