Example 2: Parse Properties configuration
The basic configuration format based on the Properties file is as follows. Please also name the file configuration.properties and place it in the cfgs directory under the
config_home
path:#-------------------------------------------------------------------------- # 配置文件内容格式: properties.<categoryName>.<propertyName>=[propertyValue] # # 注意: attributes将作为关键字使用, 用于表示分类, 属性, 集合和MAP的子属性集合 #-------------------------------------------------------------------------- # 举例1: 默认分类下表示公司名称, 默认分类名称为default properties.default.company_name=Apple Inc. #-------------------------------------------------------------------------- # 数组和集合数据类型的表示方法: 多个值之间用'|'分隔, 如: Value1|Value2|...|ValueN #-------------------------------------------------------------------------- properties.default.products=iphone|ipad|imac|itouch #-------------------------------------------------------------------------- # MAP<K, V>数据类型的表示方法: # 如:产品规格(product_spec)的K分别是color|weight|size|age, 对应的V分别是热red|120g|small|2015 #-------------------------------------------------------------------------- properties.default.product_spec.color=red properties.default.product_spec.weight=120g properties.default.product_spec.size=small properties.default.product_spec.age=2015 # 每个MAP都有属于其自身的属性列表(深度仅为一级), 用attributes表示, abc代表属性key, xyz代表属性值 # 注: MAP数据类型的attributes和MAP本身的表示方法达到的效果是一样的 properties.default.product_spec.attributes.abc=xyz
Modify the configuration class DemoConfig as follows, specify the configuration file content parser through the
@ConfigurationProvider
annotation:@Configuration("cfgs/configuration.properties") @ConfigurationProvider(PropertyConfigurationProvider.class) 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(); } }
Re-execute the example code, the execution result is the same as Example 1:
Apple Inc. {abc=xzy, color=red, size=small, weight=120g, age=2015} [itouch, imac, ipad, iphone]