configuration2 使用

本文介绍了一种自定义配置文件加载器的实现方法,该加载器能够从核心配置文件中读取路径列表,并根据这些路径加载不同类型的配置文件(如XML、XPath XML和Properties)。此外,还提供了文件热更新的支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.configuration.reloading.ReloadingStrategy;
import org.apache.commons.configuration2.CompositeConfiguration;
import org.apache.commons.configuration2.XMLConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.tree.xpath.XPathExpressionEngine;

import java.util.List;

/**
 * 自定义读取配置文件
 * Created by qijunhuang on 2017/7/20.
 */
public enum ConfigSingleton {
    INSTANCE;
    public CompositeConfiguration getConfig(String coreStr, String listkey) {
        //读总配置文件
        try {

            Configurations configs = new Configurations();
            XMLConfiguration config = configs.xml(coreStr);
            if (config == null) {
                return null;
            }
            CompositeConfiguration readConfigs=new CompositeConfiguration();
            // ReloadingStrategy strategy = new FileChangedReloadingStrategy();
           // readConfigs.setReloadingStrategy(strategy);
            List<String> paths = config.getList(String.class, listkey);
            if(paths==null||paths.size()<=0)
            {
                return readConfigs;
            }
            for(String fileName:paths) {
                String fileType = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
                switch (fileType)
                {
                    case "xml":
                       XMLConfiguration xmlc=configs.xml(fileName);
                        readConfigs.addConfiguration(xmlc,true);
                        break;
                    case "xpath":
                        XMLConfiguration xmlxpath=configs.xml(fileName);
                        xmlxpath.setExpressionEngine(new XPathExpressionEngine());
                        readConfigs.addConfiguration(xmlxpath,true);
                        break;
                    case "properties":
                        readConfigs.addConfiguration(configs.properties(fileName),true);
                        break;
                }

            }
            return readConfigs;
        } catch (Exception ex) {

            return null;
        }
    }
}
这只是读多个配置文件,其功能及优化请自行研究

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值