使用Apache Commons Configuration读取配置信息
在项目中使用一些比较新的库总会给你带来很多快乐,在这篇文章中,我将会给你介绍一个在Java中读取配置文件的框架——Apache Commons Configuration framework.
你会了解到
·在程序改变后自动重新加载配置。
Maven设置
<dependencies>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>commons-jxpath</groupId>
<artifactId>commons-jxpath</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
简单的数据库配置
<?xmlversion="1.0"encoding="UTF-8"?>
<!-- const.xml -->
<config>
<database>
<url>127.0.0.1</url>
<port>1521</port>
<login>admin</login>
<password>pass</password>
</database>
</config>
为了拿到url和port我们用如下的代码:
XMLConfiguration config =new XMLConfiguration("const.xml");
// 127.0.0.1
config.getString("database.url");
// 1521
config.getString("database.port");
XMLConfiguration是一个Apache Commons类,他可以从指定的配置文件中加载内容,并且提供一个很好的以指定的点的方式得到存储的值。例如例子中的表达式database.port映射到xml文件中的 config/database/port节点的值“1521”。当然还有很多方式获取数据。这里有一些基本的用法:
getBoolean
getByte
getDouble
getFloat
getInt
getInteger
getList
getLong
getStringArray
将如上配置扩展一步
<?xmlversion="1.0"encoding="UTF-8"?>
<!-- const.xml -->
<config>
<databases>
<database>
<name>dev</name>
<url>127.0.0.1</url>
<port>1521</port>
<login>admin</login>
<password>pass</password>
</database>
<database>
<name>production</name>
<url>192.23.44.100</url>
<port>1521</port>
<login>admin</login>
<password>not-so-easy-pass</password>
</database>
</databases>
</config>
现在我们要访问url数据我们可以这样:
XMLConfiguration config =new XMLConfiguration("const.xml"); // 127.0.0.1
config.getString("databases.database(0).url"); // 192.23.44.100
config.getString("databases.database(1).url");
XPath表达式
XMLConfiguration config =new XMLConfiguration("const.xml");
config.setExpressionEngine(new XPathExpressionEngine()); // 127.0.0.1
config.getString("databases/database[name = 'dev']/url"); // 192.23.44.100
config.getString("databases/database[name = 'production']/url");
这里是上面两个XPath表达式查询的一个解释:
访问环境变量
EnvironmentConfiguration config =new EnvironmentConfiguration();
config.getString("ENV_TYPE");
假设变量ENV_TYPE已经设置好了,想看上面的程序是否运行正确,你可以在控制台运行如下脚本:
echo %ENV_TYPE% # for Windows
# or...
echo $ENV_TYPE # for Linux/Mac OS
联合配置
public String getDbUrl() throws ConfigurationException {
EnvironmentConfiguration envConfig =new EnvironmentConfiguration();
String env = envConfig.getString("ENV_TYPE");
if("dev".equals(env) ||"production".equals(env)) {
XMLConfiguration xmlConfig =new XMLConfiguration("const.xml");
xmlConfig.setExpressionEngine(new XPathExpressionEngine());
String xpath ="databases/database[name = '"+ env +"']/url";
return xmlConfig.getString(xpath);
}else{
String msg ="ENV_TYPE environment variable is "+
"not properly set";
throw new IllegalStateException(msg);
}
}
集中你的配置
<?xmlversion="1.0"encoding="UTF-8"?>
<!-- config.xml -->
<configuration>
<env/>
<xmlfileName="const.xml"/>
</configuration>
你需要使用DefaultConfigurationBuilder类,最终版本的getDbUrl方法看起来像这样:
public String getDbUrl()throws ConfigurationException {
DefaultConfigurationBuilder builder =
new DefaultConfigurationBuilder("config.xml");
boolean load =true;
CombinedConfiguration config = builder.getConfiguration(load);
config.setExpressionEngine(new XPathExpressionEngine());
String env = config.getString("ENV_TYPE");
if("dev".equals(env) ||"production".equals(env)) {
String xpath ="databases/database[name = '"+ env +"']/url";
return config.getString(xpath);
}else{
String msg ="ENV_TYPE environment variable is "+
"not properly set";
throw new IllegalStateException(msg);
}
}
自动重新加载
XMLConfiguration config =new XMLConfiguration("const.xml");
ReloadingStrategy strategy =new FileChangedReloadingStrategy();
strategy.setRefreshDelay(5000);
config.setReloadingStrategy(strategy);
或者把他写到主配置文件中:
<?xmlversion="1.0"encoding="UTF-8"?>
<!-- config.xml -->
<configuration>
<env/>
<xmlfileName="const.xml">
<reloadingStrategyrefreshDelay="5000"
config-class="org.apache.commons.configuration.reloading.FileChangedReloadingStrategy"/>
</xml>
</configuration>
最后
·自动解析配置文件的实际路径(不管你是把它放在程序文件夹下还是一个jar中。)
使用Apache Commons Configuration读取配置信息的更多相关文章
- Apache Commons Configuration读取xml配置
近期项目自己手写一个字符串连接池.因为环境不同有开发版本.测试版本.上线版本.每一个版本用到的数据库也是不一样的.所以需要能灵活的切换数据库连接.当然这个用maven就解决了.Apache Commo ...
- JavaWEB中读取配置信息
第一种方法是使用java.io和java.util包,缺点是路径的概念要清晰, 例子: Properties prop = new Properties(); InputStream in = get ...
- Apache Commons Configuration的应用
Apache Commons Configuration的应用 Commons Configuration是一个java应用程序的配置管理工具.可以从properties或者xml文件中加载软件的配置 ...
- ASP.NET Core的配置(1):读取配置信息
提到"配置"二字,我想绝大部分.NET开发人员脑海中会立马浮现出两个特殊文件的身影,那就是我们再熟悉不过的app.config和web.config,多年以来我们已经习惯了将结构化 ...
- NameValueCollection类读取配置信息
C#中的NameValueCollection类读取配置信息,大家可以参考下. 我首先介绍配置文件中的写法: 1.在VS2015中的工程下建立一个控制台应用程序,其config文件默认名称为App ...
- SQL2005SP4补丁安装时错误: -2146233087 MSDTC 无法读取配置信息。。。错误代码1603的解决办法
是在安装slq2005sp3和sp4补丁的时候碰到的问题. 起先是碰到的错误1603的问题,但网上搜索的1603的解决办法都试过了,google也用了,外文论坛也读了,依然没有能解决这个问题. 其实一 ...
- AspNet Core 程序写入配置信息并再次读取配置信息
1.首先创见Core控制台应用程序 并且引入 AspNetCore.All 首先我们写入配置信息:直接代码如下 //配置信息的根对象 public static IConfigurationRoo ...
- ASP.NET Core实现强类型Configuration读取配置数据
前言 实现读取JSON文件几种方式,在项目中采取老办法简单粗暴,结果老大过来一看,恩,这样不太可取,行吧那我就用.NET Core中最新的方式诺,切记,适合的才是最好的,切勿懒. .NET Core读 ...
- Apache Commons configuration使用入门
使用Commons Configuration可以很好的管理我们的配置文件的读写, 官网:http://commons.apache.org/configuration 需要用到commons-la ...
随机推荐
- Python_Day3_基础3
python基础之数据类型与变量 字典 字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划.字母来查对应页的详细内容. 语法: info = { 'stu1101': &q ...
- Security » Authorization » 基于自定义策略的授权
Custom Policy-Based Authorization¶ 基于自定义策略的授权 98 of 108 people found this helpful Underneath the cov ...
- Spring IoC原理详解
去掌握一门技术的时候,往往很多人都忽略了一点,只是一味地去写代码,原理层面的东西从来就不理会 还有就是学习的过程中,不去想为什么有了当前的写法,却有着这么一门技术可以代替它 一般来说,在写程序的时候, ...
- STM32上移植ds1307笔记
PS:网上关于ds1307的资料最多还是基于51等单片机的,和stm32上还是略有差别,代码是参考了http://www.openedv.com/posts/list/20167.htm 但是他的代码 ...
- logistic回归模型
一.模型简介 线性回归默认因变量为连续变量,而实际分析中,有时候会遇到因变量为分类变量的情况,例如阴性阳性.性别.血型等.此时如果还使用前面介绍的线性回归模型进行拟合的话,会出现问题,以二分类变量为例 ...
- Linux服务器
/*** cloud_sum_server ***/void cloud_sum(int sockfd) { ssize_t n; char buf[MAXLINE]; , b = ; again: ...
- JQuery在循环中绑定事件的问题详解
JQuery在循环中绑定事件的问题详解 有个页面上需要N个DOM,每个DOM里面的元素ID都要以数字结尾,比如说 ? 1 2 3 <input type="text" nam ...
- Stack的pop和push操作
#include <stack> #include <cstdio> using namespace std; int main(){ stack<int> s; ...
- 读javascript高级程序设计08-引用类型之Global、Math、String
一.Global 所有在全局作用域定义的属性和方法,都属于Global对象. 1.URI编码: encodeURI():主要用于对整个URI编码.它不会对本身属于URI的特殊字符进行编码. encod ...
- powershell中的两只爬虫
--------------------序-------------------- (PowerShell中的)两只爬虫,两只爬虫,跑地快,爬网页不赖~~~ 一只基于com版的ie,一只基于.net中 ...