개요

PropertiesConfiguration 은  apache commons-configuration 에 포함된 클래스로 java.util.Properties 의 대체 라이브러리이다.

Property 에 비해 다양한 기능을 제공하고 사용하기 손쉬운 장점이 있다.


사용

maven dependancy

<dependency>
  <groupId>commons-configuration</groupId>
  <artifactId>commons-configuration</artifactId>
  <version>1.9</version>
</dependency>
XML

Using PropertiesConfiguration

loading & access

  1. 다음과 같은 usergui.properties 있을 때

    # Properties definining the GUI
    colors.background = #FFFFFF
    colors.foreground = #000080
    
    window.width = 500
    window.height = 300
    CODE



  2. 프로퍼티 파일 로딩

    // path 를 절대 경로로 주지 않았을 경우 다음 경로에서 찾게 됨
    //1. current directory
    //2. user home directory
    //3. classpath
    Configuration config = new PropertiesConfiguration("usergui.properties");
    JAVA
  3. property 가 로딩되었으면 다음과 같이 Cofiguration interface 를 통해 property 에 접근할 수 있음

    String backColor = config.getString("colors.background");
    Dimension size = new Dimension(config.getInt("window.width"),
      config.getInt("window.height"));
    JAVA

Include

property name 이 "include" 이고 value 가 disk 에 있는 property 파일의 이름일 경우 해당 파일의 내용을 현재 property 에 포함시키게 됨.

usergui.properties
# usergui.properties

include = colors.properties
include = sizes.properties
colors.properties
# colors.properties

colors.background = #FFFFFF


List and arrays

다음과 같이 하나의 property 의 value 에 list 나 array 로 설정하는게 가능

# chart colors
colors.pie = #FF0000, #00FF00, #0000FF

해당 값은 array 나 java.util.List 를 통해 추출할 수 있음.

String[] colors = config.getStringArray("colors.pie");
List colorList = config.getList("colors.pie");
JAVA


Saving

configuration 이 변경되었을 경우 save() method 를 이용하여 반영할수 있음.

PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
config.setProperty("colors.background", "#000000);
config.save();
CODE

You can also save a copy of the configuration to another file:

PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
config.setProperty("colors.background", "#000000);
config.save("usergui.backup.properties);
CODE



Ref