---
title: "Java之Jconfig 学习"
author: "logqq"
date: "2013-05-24T11:21:47Z"
tags: []
categories: ["开源软件"]
slug: "java-jconfig"
draft: false
lastmod: "2013-05-24T11:21:47Z"
id: 1874542
url: "https://logqq.iteye.com/blog/1874542"
---

因为properties的局限性，有时候得使用XML文件来定义应用的配置参数，jConfig 正是这样一个读写XML配置文件的工具。开发者在 Java 程序中只需要使用get/set方法就能读取修改 XML 文件中的配置参数。jConfig 目前只支持两层结构，最新版本为 2.9。

该项目主页:[http://www.jconfig.org/](http://www.jconfig.org/)

1.新建工程demo,src下创建config.xml，demo\_config.xml文件

```
<?xml version="1.0" encoding="iso-8859-1" ?>
<properties>
  <variables>
    <variable name="my.path" value="/home/foo/data"/>
  </variables>
  <category name="general">
    <property name="upload_dir" value="${my.path}/data"/>
    <property name="NewsCounter" value="10"/>
    <property name="showNews" value="true"/>
    <property name="MyProp" value="Hello world"/>
    <property name="USER" value="user1"/>
  </category>
  <category name="JDBC">
    <property name="URL" value="jdbc:mysql://localhost/iportal"/>
    <property name="DRIVER" value="org.gjt.mm.mysql.Driver"/>
    <property name="PWD" value="pwd"/>
    <property name="USER" value="user2"/>
  </category>
</properties>

```

 

2.加载xml的配置

读取默认的config.xml

```
private static final Configuration configuration = ConfigurationManager.getConfiguration();
```

 

读取demo\_config.xml

```
private static final Configuration configuration = ConfigurationManager.getConfiguration("demo");
```

 

 

3.具体操作如下：

```
package com.jconfig;

import org.jconfig.Configuration;
import org.jconfig.ConfigurationManager;

public class DemoJConfig {
	private static final Configuration configuration = ConfigurationManager.getConfiguration("demo");

	public static void main(String[] args) {
		//读取路径，路径中包括variable
		String myProp = configuration.getProperty("upload_dir");
		System.out.println("MyProp:" + myProp);
		String jdbcUser = configuration.getProperty("USER", null, "JDBC");
		System.out.println("jdbcUser:" + jdbcUser);
		int newsCounter = configuration.getIntProperty("NewsCounter", -1);
		if (newsCounter == 10) {
			System.out.println("We have found the correct value");
		}
		boolean showNews = configuration.getBooleanProperty("showNews", false);
		if (showNews) {
			System.out.println("We have to show the news");
		}

		
	}
}
```

 

结果如下：

```
MyProp:/home/foo/data/data
jdbcUser:user2
We have found the correct value
We have to show the news
```

 

更多例子见附件