在各个项目中,总会用到各种数据库连接或连接池等基础信息。如果使用常量写在程序里,恐怕不利于修改配置和部署。这里总结一个在工作中常用的配置文件的工具类。
由于这个类主要读取的是数据库配置,因此类名为DatabaseProject,当然读取不同配置也可以使用其他类名。
public final class DatabaseProject {
public static final Logger LOGGER = LoggerFactory.getLogger(DatabaseProject.class);
//You must call init() before really use DB.
public static CompositeConfiguration DB_CONFIG = new CompositeConfiguration();
public static void init(String confDir)
{
DB_CONFIG = getConfiguration(confDir,"db.properties");
}
public static CompositeConfiguration getConfiguration(String confDir,
String prop) {
CompositeConfiguration config = new CompositeConfiguration();
File file = new File(confDir + "/" + prop);
FileChangedReloadingStrategy reloadingStrategy = new FileChangedReloadingStrategy();
reloadingStrategy.setRefreshDelay(10000);// 10s
URL url = null;
try {
if (file.exists()) {
url = file.toURI().toURL();
} else {
url = org.apache.commons.configuration.ConfigurationUtils
.locate(prop);
}
LOGGER.info("loading conf from:" + url);
PropertiesConfiguration fileConfiguraton = new PropertiesConfiguration();
fileConfiguraton.load(url);
fileConfiguraton.setReloadingStrategy(reloadingStrategy);
config.addConfiguration(fileConfiguraton);
} catch (Exception e) {
LOGGER.error("Failed to load config:" + prop, e);
}
return config;
}
public static void main(String[] args){
DatabaseProject.init("src");
}
}
这个类中主要使用了apache的commons-configuration包,日志使用slf4j、logback等jar包。
主要方法是getConfiguration,获取properties文件配置路径和文件名,并启用FileChangedReloadingStrategy文件修改后重新加载策略,返回CompositeConfiguration实例。
使用方法:
DatabaseProject.init("src");//初始化传入配置文件路径
//
DatabaseProject.DB_CONFIG.containsKey("mongodb.ips")
DatabaseProject.DB_CONFIG.getString("mongodb.ip");
DatabaseProject.DB_CONFIG.getInt("mongodb.port");
以上就是这个工具类简单的使用介绍,commons-configuration包还提供了有不少工具,大家后续可以查看API文档再慢慢完善这个类。