티스토리 뷰

Java

[Apache Commons]Configuration

나야 2009. 6. 10. 21:00
http://commons.apache.org/configuration/

연구실에서 프로젝트를 할 때, DB 계정 정보 등의 설정 정보 등을 XML파일로 적어놓고 참조하려고 마음을 먹었습니다. 그래서  XML파일 읽는 코드를 한 20줄 짜고, 이 설정 정보를 java.util.Properties 에 저장하여 메모리에 유지하도록 static 하게 변수를 선언하는 등의 작업을 하였으나, 검색해보니 Apache Commons 프로젝트에 Configuration 이라는 컴포넌트가 있습니다.

구글에서 검색하니 http://twit88.com/blog/2007/09/18/xml-configuration-for-java-program/  에도 간단한 예가 나와있습니다. 어쨌든, http://commons.apache.org/configuration/userguide/user_guide.html 를 보시면 이 컴포넌트의 사용방법이 자세하게 기술되어 있습니다. 그리고 User guide의 Hierarchical Properties 항목을 보면, XML파일을 이용하는 방법이 기술되어 있습니다. 

간단히 따라해보았습니다.
먼저 conf.xml 라는 이름의 xml 설정파일을 만들었습니다. 

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<database>
		<server>
			<type>PostgreSQL</type>
			<host>localhost</host>
			<port>5432</port>
		</server>
		<user>				
			<name>coinus</name>
			<password>1124</password>
		</user>
		<database>
			<name>coinus</name>
			<charset>UTF8</charset>
		</database>
	</database>		
</config>
다음은 XMLConfiguration 를 사용해서 XML파일을 읽는 간단한 예제입니다.

package kr.ac.uos.dmlab.config;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;

public class ConfigLoader {
	
	private static XMLConfiguration load(String file) {
		XMLConfiguration conf= null;
		try {
			conf= new XMLConfiguration("conf/conf.xml");
			
			System.out.println(conf.getString("database.server.type"));
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
		return conf;
	}
	
	public static void main(String[] args) {
		load("conf/conf.xml");
	}
	
}
load()  메소드 중간에 root element인 config 밑의 database 밑의 server 밑의 'type' element의 문자열 값을 가져와서 출력하는 코드가 13 line에 있습니다. 이렇게 element의 value를 문자열이나 정수형 등으로 가져올 수 있습니다. 물론 attribute도 사용할 수 있습니다. 자세한 내용은 User Guide의 Hierarchical Properties 를 참조해주세요. ^^;;

아 그리고 Configuration 컴포넌트의 코드에서 Commons의 다른 컴포넌트들, lang, collections, logging 등이 사용됩니다. 모두 다운 받아서 추가해주어야 합니다. 현재로서는 많은 기능이 필요한 것은 아니지만, 머 훌륭한 코드들일테니 배워두어서 나쁠리 없겠죠.

[딴얘기]
http://gyuha.tistory.com/193 를 감사히 보고 써보니 정말 좋은 것 같군요. 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함