Example 1: Parse XML configuration


  • The basic configuration format based on XML files is as follows. In order to match the test code, please name the file configuration.xml and place it in the cfgs directory under the config_home path Here:

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- XML根节点为properties -->
    <properties>
    
        <!-- 分类节点为category, 默认分类名称为default -->
        <category name="default">
    
            <!-- 属性标签为property, name代表属性名称, value代表属性值(也可以用property标签包裹) -->
            <property name="company_name" value="Apple Inc."/>
    
            <!-- 用属性标签表示一个数组或集合数据类型的方法 -->
            <property name="products">
                <!-- 集合元素必须用value标签包裹, 且value标签不要包括任何扩展属性 -->
                <value>iphone</value>
                <value>ipad</value>
                <value>imac</value>
                <value>itouch</value>
            </property>
    
            <!-- 用属性标签表示一个MAP数据类型的方法, abc代表扩展属性key, xyz代表扩展属性值, 扩展属性与item将被合并处理  -->
            <property name="product_spec" abc="xzy">
                <!-- MAP元素用item标签包裹, 且item标签必须包含name扩展属性(其它扩展属性将被忽略), 元素值由item标签包裹 -->
                <item name="color">red</item>
                <item name="weight">120g</item>
                <item name="size">small</item>
                <item name="age">2015</item>
            </property>
        </category>
    </properties>
  • Create a new configuration class DemoConfig, and specify the relative path of the configuration file through the @Configuration annotation

    @Configuration("cfgs/configuration.xml")
    public class DemoConfig extends DefaultConfiguration {
    }
  • Test code, complete module initialization and load configuration file content:

    public static void main(String[] args) throws Exception {
        YMP.get().init();
        try {
            DemoConfig _cfg = new DemoConfig();
            if (Cfgs.get().fillCfg(_cfg)) {
                System.out.println(_cfg.getString("company_name"));
                System.out.println(_cfg.getMap("product_spec"));
                System.out.println(_cfg.getList("products"));
            }
        } finally {
            YMP.get().destroy();
        }
    }
  • Execution result:

    Apple Inc.
    {abc=xzy, color=red, size=small, weight=120g, age=2015}
    [itouch, imac, ipad, iphone]