Monday, April 18, 2005

Commons Configuration

ปกติเวลาเราเขียน application
ถ้าเราต้องการให้ application ยืดหยุ่น
หรือสามารถทำ custom configuration
ได้โดยไม่ต้อง build หรือ compile ใหม่
เราก็จะต้องแยกตัวแปรจำนวนหนึ่งออกมา
โดยอาจจะเก็บใน flat file หรือเก็บ
ใน database

ตัว Commons Configuration
เป็น api ที่ช่วยให้เราเขียนส่วน configuration
ได้เร็วและง่ายขึ้น

feature แรกก็คือเราสามารถเลือก Datasource
ของ configuration ได้หลายรูปแบบ (เลือกหลายๆอันพร้อมๆกันได้ด้วย)
  • Properties files
  • XML documents
  • JNDI
  • JDBC Datasource
  • System properties
  • Applet parameters
  • Servlet parameters

ส่วนการใช้งาน เราสามารถที่จะเลือก
initialize แบบเฉพาะเจาะจง
Configuration config = new PropertiesConfiguration("usergui.properties");

หรือเลือกใช้ผ่าน Factory Pattern ได้
ConfigurationFactory factory = new ConfigurationFactory("config.xml");
Configuration config = factory.getConfiguration();

โดย config.xml จะมีหน้าตาประมาณนี้
<configuration>
<system/>
<properties fileName="application.properties"/>
<xml fileName="conf/test.xml"/>
<jndi prefix="java:comp/env"/>
</configuration>

ในที่นี้จะลองยกตัวอย่างการใช้งาน
เฉพาะกรณี properties file
ว่าสามารถทำอะไรได้บ้าง
  • ใน properties file สามารถอ้าง Include properties file อื่นๆได้อีก
    include = colors.properties

  • สามารถสั่ง Automatic Reloading ได้
    (กรณีที่มีการเปลี่ยนแปลง properties file ระหว่างการใช้งาน)
    PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
    config.setReloadingStrategy(new FileChangedReloadingStrategy());

  • ทำ Variable Interpolation ได้
    app.name=pok
    app.version=1.0
    app.title=${app.name}-${app.version}

  • สั่ง autosave ได้
    PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
    config.setAutoSave(true);

  • support list, array property
    colors.pie = #FF0000, #00FF00, #0000FF

    เวลาเรียกใช้ก็
    String[] colors = config.getStringArray("colors.pie");

    หรืออาจจะเขียน property ในรูป
    colors.pie = #FF0000;
    colors.pie = #00FF00;
    colors.pie = #0000FF;

Related link from Roti

No comments: