使用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 ...
随机推荐
- dataserver test code
main.go package main import ( "database/sql" "fmt" "log" "net/htt ...
- Eclipse 的 Debug 介绍与技巧
转载: Eclipse 的 Debug 介绍与技巧
- preload pic
http://www.farinspace.com/jquery-image-preload-plugin/
- 坑爹的属性,android:descendantFocusability用法简析
开发中很常见的一个问题,项目中的listview不仅仅是简单的文字,常常需要自己定义listview,自己的Adapter去继承 BaseAdapter,在adapter中按照需求进行编写,问题就出现 ...
- 线性布局通过适配器可以动态加载view
因为适配器的getView的返回对象是view, 所以线性布局的对象可以通过addView动态加载适配器的getView 举例: mTestAdapter = new ListAdapter(this ...
- 配置jdk
java_home :D:\apps\common\jdk\jdk8\jdk18045\jdk1.8.0_45 classpath: .;%JAVA_HOME%\lib\dt.jar;%JAVA_HO ...
- 转:在支持ARC工程中编译不支持ARC的文件
转:http://blog.csdn.net/duxinfeng2010/article/details/8709697 实践总结:-fno-objc-arc 设置 解决了 旧代码中存在 releas ...
- iOS开发UI篇—无限轮播(功能完善)
iOS开发UI篇—无限轮播(功能完善) 一.自动滚动 添加并设置一个定时器,每个2.0秒,就跳转到下一条. 获取当前正在展示的位置. [self addNSTimer]; } -(void)addNS ...
- 创建.htaccess文件
在linux下创建.htaccess文件非常简单,直接新建一个文件并重命名为.htaccess即可. 下面我来讲下如何在Window下创建.htaccess文件 一般在本地电脑上是无法建立 .htac ...
- [ie兼容]ie7 margin-bottom失效
有时候子元素设置了margin,父元素也设置了margin,父元素的margin在ie7下会失效(包括padding) 解决方法:父容器加属性overflow:hidden;zoom:100%;