初始化配置参数

来源:互联网 发布:ios windows 编辑:程序博客网 时间:2024/04/29 13:20
初始化配置参数
<listener>
    <listener-class>
        com.companyname.cms.ms.commons.listener.InitListener
    </listener-class>
</listener>
package com.companyname.cms.ms.commons.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.springframework.util.Log4jConfigurer;

import com.companyname.dhm.common.config.impl.ConfigFactory;
import com.companyname.dhm.common.init.SystemInitiator;

/**
 * @功能:初始化配置参数
 * @作者:
 * @时间:Jul 30, 2013 5:55:00 PM
 */
public class InitListener implements ServletContextListener
{
    private static final Logger logger = Logger.getLogger(InitListener.class);

    public void contextDestroyed(ServletContextEvent arg0)
    {
         
    }

    public void contextInitialized(ServletContextEvent ctx)
    {
        String FS = System.getProperty("file.separator");
        ServletContext context = ctx.getServletContext();

        // 初始化项目的一些信息 比如config log目录 项目名
        SystemInitiator.initApp(context);

        System.out.println("MS: Init log...");
        String logFile = context.getInitParameter("log.config-file");
        if (logFile == null || logFile.trim().length() == 0)
        {
            System.out.println("MS: log.config-file is not configed, so not initial!!! ");
        }
        else
        {
            // 日志配置文件
            String logConfigFileLocation = SystemInitiator.getSystemInfo().getConfPath() + FS + logFile;
            try
            {
                // 日志刷新间隔时间
                int refreshInterval = Integer.parseInt(context.getInitParameter("log.config-file-refresh-interval"));
                System.out.println("logConfigFileLocation=" + logConfigFileLocation + ",refreshInterval="
                        + refreshInterval);
                Log4jConfigurer.initLogging(logConfigFileLocation, refreshInterval);
            }
            catch (Exception e)
            {
                System.out.println("MS: Initail log4f config error:" + e.getMessage());
                System.exit(1);
            }
        }

        // initial log configuration
        System.out.println("MS: Initial system configuration...");
        String configFile = context.getInitParameter("config.system-config-file");
        if (configFile == null || configFile.trim().length() == 0)
        {
            System.out.println("MS: config.system-config-file is not configed, so not initial!!! ");
        }
        else
        {
            new ConfigFactory().initConfig(SystemInitiator.getSystemInfo().getConfPath(), configFile,3000);
        }
    }

}

ConfigFactory
package com.companyname.dhm.common.config.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;

import com.companyname.dhm.common.util.MonitorXmlFileTask;

/**
 * ConfigFactory.java
 * <p>Copyright: Copyright (c) 2009 <p>
 * <p>Company: </p>
 *  @author    
 *  @version   1.0
 */
public class ConfigFactory
{

    private static Logger log = Logger.getLogger(ConfigFactory.class);
    
    public ConfigFactory()
    {

    }

    /**
     * 初始化配置
     * @param path:sysConfig.xml的路径
     */
    public void initConfig(String confPath, String file, int refresh)
    {

        String FS = System.getProperty("file.separator");

        if (file == null)
        {

            log.error("配置文件SysConfig.xml路径地址尚未初始化,请查看web.xml文件");
            return;
        }

        XMLConfiguration config = null;
        try
        {
            config = new XMLConfiguration(confPath + FS + file);
        }
        catch (ConfigurationException e)
        {

            log.error("加载配置文件 SysConfig.xml 发生错误,请查看文件是否存在,或格式是否错误");
            return;
        }
        List<String> proList = config.getList("properties.filepath");
        for (String pPath : proList)
        {

            pPath = confPath + FS + pPath;
            log.debug("开始加载配置文件 path:" + pPath);
            PropertiesFactory.addConfiguration(pPath);
        }
        List<String> xmlList = config.getList("xml.filepath");
        List<String> monitorXmlList = new ArrayList<String>();
        
        // 启动定时器,检查这些文件是否变更
        
        for (String xPath : xmlList)
        {
            xPath = confPath + FS + xPath;
            log.debug("开始加载配置文件 path:" + xPath);
            XMLFactory.addConfiguration(xPath);
            monitorXmlList.add(xPath);
        }
        
        
        // 定时监测
        Timer timer = new Timer();
        timer.schedule(new MonitorXmlFileTask(monitorXmlList), 0L, refresh);
        
        if (config.getString("data.dataConn.driverName") != null && config.getString("data.dataConn.jdbcUrl") != null
                && config.getString("data.dataConn.userName") != null
                && config.getString("data.dataConn.passWd") != null && config.getString("data.table.tableName") != null
                && config.getString("data.table.key") != null && config.getString("data.table.value") != null)
        {

            log.debug("开始加载数据库配置信息");
            // 初始化参数
            DataFactory.setParameters(config.getString("data.dataConn.driverName"),
                    config.getString("data.dataConn.jdbcUrl"), config.getString("data.dataConn.userName"),
                    config.getString("data.dataConn.passWd"), config.getString("data.table.tableName"),
                    config.getString("data.table.type"), config.getString("data.table.key"),
                    config.getString("data.table.value"));
        }
    }

}
MonitorXmlFileTask
package com.companyname.dhm.common.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import com.companyname.dhm.common.config.impl.XMLFactory;

/**
 * 监测XML配置文件是否有修改,有修改,则重新加载
 * @author
 *
 */
public class MonitorXmlFileTask extends TimerTask
{
    // 配置文件路径详情
    private List<String> xmlString = null;

    private static final Map<String, Long> HISTORY_CHANGE_TIM_MAP = new HashMap<String, Long>();;

    public MonitorXmlFileTask(List<String> xmlString)
    {
        this.xmlString = xmlString;
    }

    @Override
    public void run()
    {
        try
        {
            String filePath = "";

            Long historyChangeTime;

            // 遍历文件,检测是否修改
            for (int i = 0; i < xmlString.size(); i++)
            {
                filePath = xmlString.get(i);

                // 获取历史状态
                historyChangeTime = HISTORY_CHANGE_TIM_MAP.get(filePath);

                // 当前修改时间
                File file = new File(filePath);
                Long currentChangeTime = file.lastModified();
                if (null == historyChangeTime || historyChangeTime.equals(""))
                {
                    HISTORY_CHANGE_TIM_MAP.put(filePath, currentChangeTime);
                }
                else
                {
                    // 如果时间不相等,证明有修改,需要重新加载
                    if (!currentChangeTime.equals(historyChangeTime))
                    {
                        XMLFactory.addConfiguration(filePath);
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

XMLFactory
package com.companyname.dhm.common.config.impl;

import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;

import com.companyname.dhm.common.config.base.CompositeConfig;
import com.companyname.dhm.common.util.StringUtil;

/**
 * XMLFactory.java
 * <p>Copyright: Copyright (c) 2009 <p>
 * <p>Company: </p>
 *  @author    
 *  @version   1.0
 */
public class XMLFactory
{

    private static Logger log = Logger.getLogger(XMLFactory.class);
    private final static CompositeConfig config = new CompositeConfig();
    private static boolean initFlag = false;
    private static final Map<String, XMLConfiguration> XML_MAP = new Hashtable<String, XMLConfiguration>();
    private XMLFactory()
    {

    }

    /**
     * 增加新的配置文件信息
     * @param path 配置文件地址
     */
    public synchronized static void addConfiguration(String path)
    {
        initFlag = true;
        try
        {
            XMLConfiguration configuration = XML_MAP.get(path);
            if (null != configuration)
            {
                XMLConfiguration newConfiguration = new XMLConfiguration(path);
                XML_MAP.put(path, newConfiguration);
                configuration.setEncoding("UTF-8");
                config.addConfiguration(newConfiguration);
                
                // 等新的进去后,再移除老的
                config.removeConfiguration(configuration);
            }
            else
            {
                configuration = new XMLConfiguration(path);
                XML_MAP.put(path, configuration);
                configuration.setEncoding("UTF-8");
                config.addConfiguration(configuration);
            }
            
        }
        catch (Exception e)
        {
            log.error("加载配置文件 " + path + " 发生错误,请查看文件是否存在,或格式是否错误");
        }
    }

    /**
     * 获取长整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static long getValueLong(String key)
    {
        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getLong(key);
    }

    /**
     *
     * 获取迭代器
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static Iterator getKeys()
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getKeys();
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static int getValueInt(String key)
    {
        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getInt(key);
    }

    /**
     *
     * 获取数组类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static String[] getValueArray(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getStringArray(key);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static String getValueString(String key)
    {
        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getString(key);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @param params 替换的参数,例如{"1","22","33"}
     * @return key的值
     */
    public static String getValueString(String key, String[] params)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return StringUtil.substituteParams(config.getString(key), params);
    }

    /**
     *
     * 获取双精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static double getValueDouble(String key)
    {
        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getDouble(key);
    }

    /**
     * 获取高精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static BigDecimal getValueBigDecimal(String key)
    {
        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBigDecimal(key);
    }

    /**
     * 获取浮点数字类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static float getValueFloat(String key)
    {
        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getFloat(key);
    }

    /**
     * 获取布尔类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static boolean getValueBoolean(String key)
    {
        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBoolean(key);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static BigInteger getValueBigInteger(String key)
    {
        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBigInteger(key);
    }

    /**
     * 获取List类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static List getValueList(String key)
    {
        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getList(key);
    }

    /**
     * 清除配置文件中所有的key和其值
     */
    public static void clear()
    {
        if (config != null)
        {
            config.clear();
            initFlag = false;
        }
    }

    /**
     * 保存相应的值,该值存在进行修改,不存在不处理
     * @param key 需要保存的KEY
     * @param value 需要保存的值
     */
    public static void setProperty(String key, String value)
    {
        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        config.setPropertyXML(key, value);
    }

    public static void main(String[] args) throws ConfigurationException
    {
        // for(;;){
        // XMLFactory.addConfiguration("conf/FtpConfig.xml");
        // String value = XMLFactory.getValueString("boss.configItem.port");
        // // XMLFactory.clear();
        // System.out.println(value);
        // }
        for (;;)
        {
            XMLConfiguration configuration = new XMLConfiguration("conf/FtpConfig.xml");

            System.out.println(configuration.getString("boss.configItem.port"));

        }

    }
}

CompositeConfig
package com.companyname.dhm.common.config.base;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.ConfigurationRuntimeException;
import org.apache.commons.configuration.ConfigurationUtils;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;

/**
 * CompositeConfig.java
 * <p>Copyright: Copyright (c) 2009<p>
 * <p>Company: </p>
 * @author
 * @version 1.0
 */
public class CompositeConfig extends AbstractConfiguration implements Cloneable
{

    private static Logger logger = Logger.getLogger(CompositeConfig.class);
    /** 配置列表 */
    private List configList = new LinkedList();

    /**
     * 保存配置的对象. 第一次调用新增方法时override父类的新增
     */
    private Configuration inMemoryConfiguration;

    /**
     * 构造函数
     */
    public CompositeConfig()
    {

        clear();
    }

    /**
     * 新增配置项资源文件
     *
     * @param config
     *        the configuration to add
     */
    public void addConfiguration(Configuration config)
    {

        if (!configList.contains(config))
        {
            // As the inMemoryConfiguration contains all manually added keys,
            // we must make sure that it is always last. "Normal", non composed
            // configuration add their keys at the end of the configuration and
            // we want to mimic this behaviour.
            configList.add(configList.indexOf(inMemoryConfiguration), config);

            if (config instanceof AbstractConfiguration)
            {
                ((AbstractConfiguration) config).setThrowExceptionOnMissing(isThrowExceptionOnMissing());
            }
        }
    }

    /**
     * 删除配置项
     * @param config
     */
    public void removeConfiguration(Configuration config)
    {

        // Make sure that you can't remove the inMemoryConfiguration from
        // the CompositeConfiguration object
        if (!config.equals(inMemoryConfiguration))
        {
            configList.remove(config);
        }
    }

    /**
     * 获取当前加载的配置数量
     *
     * @return the number of configuration
     */
    public int getNumberOfConfigurations()
    {

        return configList.size();
    }

    /**
     * 清空所有已加载到内存中的配置信息
     */
    public void clear()
    {

        configList.clear();
        // recreate the in memory configuration
        inMemoryConfiguration = new BaseConfiguration();
        ((BaseConfiguration) inMemoryConfiguration).setThrowExceptionOnMissing(isThrowExceptionOnMissing());
        ((BaseConfiguration) inMemoryConfiguration).setListDelimiter(getListDelimiter());
        ((BaseConfiguration) inMemoryConfiguration).setDelimiterParsingDisabled(isDelimiterParsingDisabled());
        configList.add(inMemoryConfiguration);
    }

    /**
     * 增加新的配置项
     *
     * @param key
     * @param token
     */
    protected void addPropertyDirect(String key, Object token)
    {

        inMemoryConfiguration.addProperty(key, token);
    }

    /**
     * 增加新的配置项,仅支持XML格式
     *
     * @param key
     * @param token
     */
    public void setPropertyXML(String key, Object obj)
    {

        for (Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration) i.next();
            if (config.containsKey(key))
            {
                ((XMLConfiguration) config).setProperty(key, obj);
                try
                {
                    ((XMLConfiguration) config).save();
                }
                catch (ConfigurationException e)
                {
                    logger.error("更新配置项 key:" + key + ";value:" + obj + " 失败");
                }
            }
        }
    }

    /**
     * 增加新的配置项,仅支持Properties格式
     *
     * @param key
     * @param token
     */
    public void setPropertyProperties(String key, Object obj)
    {

        for (Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration) i.next();
            if (config.containsKey(key))
            {
                ((PropertiesConfiguration) config).setProperty(key, obj);
                try
                {
                    ((PropertiesConfiguration) config).save();
                }
                catch (ConfigurationException e)
                {
                    logger.error("更新配置项 key:" + key + ";value:" + obj + " 失败");
                }
            }
        }
    }

    /**
     * 获取key对应的value
     *
     * @param key
     * @return value
     */
    public Object getProperty(String key)
    {

        Configuration firstMatchingConfiguration = null;
        for (Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration) i.next();
            if (config.containsKey(key))
            {
                firstMatchingConfiguration = config;
                break;
            }
        }

        if (firstMatchingConfiguration != null)
        {
            return firstMatchingConfiguration.getProperty(key);
        }
        else
        {
            return null;
        }
    }

    /**
     * 获取key对应的迭代器
     * @return Iterator
     */
    public Iterator getKeys()
    {

        List keys = new ArrayList();
        for (Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration) i.next();

            Iterator j = config.getKeys();
            while (j.hasNext())
            {
                String key = (String) j.next();
                if (!keys.contains(key))
                {
                    keys.add(key);
                }
            }
        }

        return keys.iterator();
    }

    /**
     * 获取key对应的迭代器
     * @param key
     * @return Iterator
     */
    public Iterator getKeys(String key)
    {

        List keys = new ArrayList();
        for (Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration) i.next();

            Iterator j = config.getKeys(key);
            while (j.hasNext())
            {
                String newKey = (String) j.next();
                if (!keys.contains(newKey))
                {
                    keys.add(newKey);
                }
            }
        }

        return keys.iterator();
    }

    /**
     * 校验列表是否为空
     * @param key
     * @return boolean
     */
    public boolean isEmpty()
    {

        boolean isEmpty = true;
        for (Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration) i.next();
            if (!config.isEmpty())
            {
                return false;
            }
        }

        return isEmpty;
    }

    protected void clearPropertyDirect(String key)
    {

        for (Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration) i.next();
            config.clearProperty(key);
        }
    }

    public boolean containsKey(String key)
    {

        for (Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration) i.next();
            if (config.containsKey(key))
            {
                return true;
            }
        }
        return false;
    }

    public List getList(String key, List defaultValue)
    {

        List list = new ArrayList();

        // add all elements from the first configuration containing the
        // requested key
        Iterator it = configList.iterator();
        while (it.hasNext() && list.isEmpty())
        {
            Configuration config = (Configuration) it.next();
            if (config != inMemoryConfiguration && config.containsKey(key))
            {
                appendListProperty(list, config, key);
            }
        }

        // add all elements from the in memory configuration
        appendListProperty(list, inMemoryConfiguration, key);

        if (list.isEmpty())
        {
            return defaultValue;
        }

        ListIterator lit = list.listIterator();
        while (lit.hasNext())
        {
            lit.set(interpolate(lit.next()));
        }

        return list;
    }

    public String[] getStringArray(String key)
    {

        List list = getList(key);

        // transform property values into strings
        String[] tokens = new String[list.size()];

        for (int i = 0; i < tokens.length; i++)
        {
            tokens[i] = String.valueOf(list.get(i));
        }

        return tokens;
    }

    /**
     * Return the configuration at the specified index.
     *
     * @param index
     *        The index of the configuration to retrieve
     * @return the configuration at this index
     */
    public Configuration getConfiguration(int index)
    {

        return (Configuration) configList.get(index);
    }

    /**
     * Returns the &quot;in memory configuration&quot;. In this configuration changes are
     * stored.
     *
     * @return the in memory configuration
     */
    public Configuration getInMemoryConfiguration()
    {

        return inMemoryConfiguration;
    }

    /**
     * Returns a copy of this object. This implementation will create a deep clone, i.e.
     * all configurations contained in this composite will also be cloned. This only works
     * if all contained configurations support cloning; otherwise a runtime exception will
     * be thrown. Registered event handlers won't get cloned.
     *
     * @return the copy
     * @since 1.3
     */
    public Object clone()
    {

        try
        {
            CompositeConfig copy = (CompositeConfig) super.clone();
            copy.clearConfigurationListeners();
            copy.configList = new LinkedList();
            copy.inMemoryConfiguration = ConfigurationUtils.cloneConfiguration(getInMemoryConfiguration());
            copy.configList.add(copy.inMemoryConfiguration);

            for (int i = 0; i < getNumberOfConfigurations(); i++)
            {
                Configuration config = getConfiguration(i);
                if (config != getInMemoryConfiguration())
                {
                    copy.addConfiguration(ConfigurationUtils.cloneConfiguration(config));
                }
            }

            return copy;
        }
        catch (CloneNotSupportedException cnex)
        {
            // cannot happen
            throw new ConfigurationRuntimeException(cnex);
        }
    }

    /**
     * Sets a flag whether added values for string properties should be checked for the
     * list delimiter. This implementation ensures that the in memory configuration is
     * correctly initialized.
     *
     * @param delimiterParsingDisabled
     *        the new value of the flag
     * @since 1.4
     */
    public void setDelimiterParsingDisabled(boolean delimiterParsingDisabled)
    {

        ((BaseConfiguration) getInMemoryConfiguration()).setDelimiterParsingDisabled(delimiterParsingDisabled);
        super.setDelimiterParsingDisabled(delimiterParsingDisabled);
    }

    /**
     * Sets the character that is used as list delimiter. This implementation ensures that
     * the in memory configuration is correctly initialized.
     *
     * @param listDelimiter
     *        the new list delimiter character
     * @since 1.4
     */
    public void setListDelimiter(char listDelimiter)
    {

        ((BaseConfiguration) getInMemoryConfiguration()).setListDelimiter(listDelimiter);
        super.setListDelimiter(listDelimiter);
    }

    /**
     * Returns the configuration source, in which the specified key is defined. This
     * method will iterate over all existing child configurations and check whether they
     * contain the specified key. The following constellations are possible:
     * <ul>
     * <li>If exactly one child configuration contains the key, this configuration is
     * returned as the source configuration. This may be the
     * <em>in memory configuration</em> (this has to be explicitly checked by the
     * calling application).</li>
     * <li>If none of the child configurations contain the key, <b>null</b> is returned.</li>
     * <li>If the key is contained in multiple child configurations or if the key is
     * <b>null</b>, a <code>IllegalArgumentException</code> is thrown. In this case the
     * source configuration cannot be determined.</li>
     * </ul>
     *
     * @param key
     *        the key to be checked
     * @return the source configuration of this key
     * @throws IllegalArgumentException
     *         if the source configuration cannot be determined
     * @since 1.5
     */
    public Configuration getSource(String key)
    {

        if (key == null)
        {
            throw new IllegalArgumentException("Key must not be null!");
        }

        Configuration source = null;
        for (Iterator it = configList.iterator(); it.hasNext();)
        {
            Configuration conf = (Configuration) it.next();
            if (conf.containsKey(key))
            {
                if (source != null)
                {
                    throw new IllegalArgumentException("The key " + key + " is defined by multiple sources!");
                }
                source = conf;
            }
        }

        return source;
    }

    /**
     * Adds the value of a property to the given list. This method is used by
     * <code>getList()</code> for gathering property values from the child
     * configurations.
     *
     * @param dest
     *        the list for collecting the data
     * @param config
     *        the configuration to query
     * @param key
     *        the key of the property
     */
    private static void appendListProperty(List dest, Configuration config, String key)
    {

        Object value = config.getProperty(key);
        if (value != null)
        {
            if (value instanceof Collection)
            {
                dest.addAll((Collection) value);
            }
            else
            {
                dest.add(value);
            }
        }
    }
}

StringUtil
package com.companyname.dhm.common.util;

import java.text.MessageFormat;

public class StringUtil
{

    public static String substituteParams(String msgtext, Object params[])
    {
        if (params == null || msgtext == null)
        {
            return msgtext;
        }
        MessageFormat mf = new MessageFormat(msgtext);
        return mf.format(params);
    }

}

PropertiesFactory
package com.companyname.dhm.common.config.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;

import com.companyname.dhm.common.config.base.CompositeConfig;
import com.companyname.dhm.common.util.StringUtil;

/**
 * PropertiesFactory.java
 * <p>Copyright: Copyright (c) 2009 <p>
 * <p>Company:</p>
 *  @author   
 *  @version   1.0
 */
public class PropertiesFactory
{

    private static Logger log = Logger.getLogger(PropertiesFactory.class);
    private final static CompositeConfig config = new CompositeConfig();
    private static boolean initFlag = false;

    private PropertiesFactory()
    {

    }

    /**
     * 增加新的配置文件信息
     * @param path 配置文件地址
     */
    public synchronized static void addConfiguration(String path)
    {

        initFlag = true;
        try
        {
            PropertiesConfiguration configuration = new PropertiesConfiguration(path);
            configuration.setEncoding("UTF-8");
            config.addConfiguration(configuration);
        }
        catch (ConfigurationException e)
        {
            log.error("加载配置文件 " + path + " 发生错误,请查看文件是否存在,或格式是否错误");
        }
    }

    /**
     * 获取长整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static long getValueLong(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getLong(key);
    }

    /**
     * 获取长整型类型的值,网管代理专用
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static long getNmsValueLong(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getLong(key) == 0 ? 2147483647L : config.getLong(key);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static int getValueInt(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getInt(key);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static String getValueString(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getString(key);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @param params 替换的参数,例如{"1","22","33"}
     * @return key的值
     */
    public static String getValueString(String key, String[] params)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return StringUtil.substituteParams(config.getString(key), params);
    }

    /**
     *
     * 获取双精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static double getValueDouble(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getDouble(key);
    }

    /**
     *
     * 获取迭代器
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static Iterator getKeys()
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getKeys();
    }

    /**
     *
     * 获取数组类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static String[] getValueArray(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getStringArray(key);
    }

    /**
     * 获取高精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static BigDecimal getValueBigDecimal(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBigDecimal(key);
    }

    /**
     * 获取浮点数字类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static float getValueFloat(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getFloat(key);
    }

    /**
     * 获取布尔类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static boolean getValueBoolean(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBoolean(key);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static BigInteger getValueBigInteger(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getBigInteger(key);
    }

    /**
     * 获取List类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static List getValueList(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getList(key);
    }

    /**
     * 清除配置文件中所有的key和其值
     */
    public static void clear()
    {

        if (config != null)
        {
            config.clear();
            initFlag = false;
        }
    }

    /**
     * 保存相应的值,该值存在进行修改,不存在不处理
     * @param key 需要保存的KEY
     * @param value 需要保存的值
     */
    public static void setProperty(String key, String value)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        config.setPropertyProperties(key, value);
    }

}

DataFactory
package com.companyname.dhm.common.config.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.configuration.PropertyConverter;
import org.apache.log4j.Logger;

import com.companyname.dhm.common.config.base.DataBaseConfig;
import com.companyname.dhm.common.util.StringUtil;

/**
 * DataFactory.java
 * <p>Copyright: Copyright (c) 2009 <p>
 * <p>Company: </p>
 *  @author   
 *  @version   1.0
 */
public class DataFactory
{

    private static Logger log = Logger.getLogger(DataFactory.class);

    private final static DataBaseConfig config = new DataBaseConfig();
    private static boolean initFlag = false;

    private DataFactory()
    {

    }

    /**
     * 设置数据库相应参数
     * @param sDriver_Name 数据库驱名
     * @param jdbc_url 数据库URL
     * @param userName 数据库登录用户名
     * @param passwd 数据库登录密码
     * @param table 配置表表名
     * @param typeColumn 配置表类型字段
     * @param keyColumn 配置表KEY字段
     * @param valueColumn 配置表VALUE字段
     */
    public static void setParameters(String sDriver_Name, String jdbc_url, String userName, String passwd,
            String table, String typeColumn, String keyColumn, String valueColumn)
    {

        initFlag = true;
        config.setParameters(sDriver_Name, jdbc_url, userName, passwd, table, typeColumn, keyColumn, valueColumn);
    }

    /**
     * 获取长整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static long getValueLong(String key)
    {

        return getValueLong(key, null);
    }

    /**
     * 获取长整型类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key的值
     */
    public static long getValueLong(String key, String type)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return Long.parseLong(config.getProperty(key, type));
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static int getValueInt(String key)
    {

        return getValueInt(key, null);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key的值
     */
    public static int getValueInt(String key, String type)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return Integer.parseInt(config.getProperty(key, type));
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static String getValueString(String key)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getProperty(key, null);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key的值
     */
    public static String getValueString(String key, String type)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return config.getProperty(key, type);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @param params 替换的参数,例如{"1","22","33"}
     * @return key的值
     */
    public static String getValueString(String key, String type, String[] params)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return StringUtil.substituteParams(config.getProperty(key, type), params);
    }

    /**
     * 获取字符串类型的值
     *
     * @param key 取得其值的键
     * @param params 替换的参数,例如{"1","22","33"}
     * @return key的值
     */
    public static String getValueString(String key, String[] params)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return StringUtil.substituteParams(config.getProperty(key), params);
    }

    /**
     * 获取双精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static double getValueDouble(String key)
    {

        return getValueDouble(key, null);
    }

    /**
     *
     * 获取双精度数字类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key的值
     */
    public static double getValueDouble(String key, String type)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return Double.parseDouble(config.getProperty(key, type));
    }

    /**
     * 获取高精度数字类型的值
     *
     * @param key 取得其值的键
     * @return key的值
     */
    public static BigDecimal getValueBigDecimal(String key)
    {

        return getValueBigDecimal(key, null);
    }

    /**
     * 获取高精度数字类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key的值
     */
    public static BigDecimal getValueBigDecimal(String key, String type)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return PropertyConverter.toBigDecimal(config.getProperty(key, type));
    }

    /**
     * 获取浮点数字类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static float getValueFloat(String key)
    {

        return getValueFloat(key, null);
    }

    /**
     * 获取浮点数字类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key对应的Value
     */
    public static float getValueFloat(String key, String type)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return Float.parseFloat(config.getProperty(key, type));
    }

    /**
     * 获取布尔类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static boolean getValueBoolean(String key)
    {

        return getValueBoolean(key, null);
    }

    /**
     * 获取布尔类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key对应的Value
     */
    public static boolean getValueBoolean(String key, String type)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return Boolean.parseBoolean(config.getProperty(key, type));
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static BigInteger getValueBigInteger(String key)
    {

        return getValueBigInteger(key, null);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key对应的Value
     */
    public static BigInteger getValueBigInteger(String key, String type)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        return PropertyConverter.toBigInteger(config.getProperty(key, type));
    }

    /**
     * 获取List类型的值
     *
     * @param key 取得其值的键
     * @return key对应的Value
     */
    public static List getValueList(String key)
    {

        return getValueList(key, null);
    }

    /**
     * 获取整型类型的值
     *
     * @param key 取得其值的键
     * @param type 所取值的类型
     * @return key对应的Value
     */
    public static List getValueList(String key, String type)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
        }
        List list = new ArrayList();
        list.add(config.getProperty(key, type));
        return list;
    }

    /**
     * 保存相应的值,该值存在进行修改,不存在,进行新增
     *
     * @param key 需要保存的KEY
     * @param value 需要保存的值
     */
    public static void setProperty(String key, String value)
    {

        setProperty(key, null, value);
    }

    /**
     * 保存相应的值,该值存在进行修改,不存在,进行新增
     *
     * @param key 需要保存的KEY
     * @param type 所取值的类型
     * @param value 需要保存的值
     */
    public static void setProperty(String key, String type, String value)
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
            return;
        }
        config.addProperty(key, type, value);
    }

    /**
     * 刷新该资源配置
     */
    public static void reSet()
    {

        if (!initFlag)
        {
            log.error("资源配置尚未初始化,或者资源文件不存在");
            return;
        }
        config.reSet();
    }
}


DataBaseConfig
package com.companyname.dhm.common.config.base;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Iterator;

import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.log4j.Logger;

/**
 * DataBaseConfig.java
 * <p>Copyright: Copyright (c) 2009 <p>
 * <p>Company: </p>
 *  @author    
 *  @version   1.0
 */
public class DataBaseConfig extends AbstractConfiguration
{

    private static Logger logger = Logger.getLogger(DataBaseConfig.class);
    /**
     * 用户存放数据库相关信息
     */
    private String DB_PARAM[] = { "driverName", "jdbcUrl", "userName", "passWd" };
    /**
     * 配置表表名
     */
    private String table;
    /**
     * 配置表类型字段
     */
    private String typeColumn;
    /**
     * 配置表KEY字段
     */
    private String keyColumn;
    /**
     * 配置表VALUE字段
     */
    private String valueColumn;

    /**
     * 用于存放配置项的集合
     */
    private Hashtable<String, String> tab = null;

    /**
     * @param sDriver_Name 数据库驱名
     * @param jdbc_url 数据库URL
     * @param userName 数据库登录用户名
     * @param passwd 数据库登录密码
     * @param table 配置表表名
     * @param typeColumn 配置表类型字段
     * @param keyColumn 配置表KEY字段
     * @param valueColumn 配置表VALUE字段
     */
    public void setParameters(String sDriver_Name, String jdbc_url, String userName, String passwd, String table,
            String typeColumn, String keyColumn, String valueColumn)
    {

        this.DB_PARAM[0] = sDriver_Name;
        this.DB_PARAM[1] = jdbc_url;
        this.DB_PARAM[2] = userName;
        this.DB_PARAM[3] = passwd;
        this.table = table;
        this.typeColumn = typeColumn;
        this.keyColumn = keyColumn;
        this.valueColumn = valueColumn;
        readConfig();
    }

    /**
     * 根据key获取相应的value
     * @param key
     * @return key对应的value
     */
    public String getProperty(String key)
    {

        return this.getProperty(key, null);
    }

    /**
     * 根据key,type获取相应的value
     * @param key
     * @param type
     * @return 相应的key与type对应的value
     */
    public String getProperty(String key, String type)
    {

        if (tab == null)
        {

            logger.error("数据库资源信息尚未初始化");
            return null;
        }
        if (this.typeColumn == null)
        {
            return tab.get(key);
        }
        else
        {
            return tab.get(type + "|" + key);
        }
    }

    /**
     * @return
     */
    public boolean isEmpty()
    {

        return tab == null;
    }

    /**
     * @param key
     * @return 该key在配置中是否存在,存在返回true,不存在返回false
     */
    public boolean containsKey(String key)
    {

        return this.containsKey(key, null);
    }

    /**
     * @param key
     * @param type
     * @return 该key在配置中对应的type类型中是否存在,存在返回true,不存在返回false
     */
    public boolean containsKey(String key, String type)
    {

        if (tab == null)
        {
            return false;
        }
        if (this.typeColumn == null)
        {
            return tab.containsKey(key);
        }
        else
        {
            return tab.containsKey(type + "|" + key);
        }
    }

    /**
     * 清除缓存中的数据
     */
    public void reSet()
    {

        clear();
        readConfig();
    }

    /**
     * 清除缓存中的数据
     */
    public void clear()
    {

        if (tab != null)
        {
            tab.clear();
            tab = null;
        }
    }

    /**
     * @return
     */
    public Iterator getKeys()
    {

        return null;
    }

    @Override
    protected void addPropertyDirect(String arg0, Object arg1)
    {

    }

    /**
     * 保存相应的值,该值存在进行修改,不存在,进行新增
     *
     * @param key 需要保存的KEY
     * @param value 需要保存的值
     */
    public void addProperty(String key, String value)
    {

        addProperty(key, null, value);
    }

    /**
     * 保存相应的值,该值存在进行修改,不存在,进行新增
     *
     * @param key 需要保存的KEY
     * @param type 需要保存的KEY对应的类型
     * @param value 需要保存的值
     */
    public synchronized void addProperty(String key, String type, String value)
    {

        if (tab == null)
        {

            logger.error("修改配置失败:资源配置尚未初始化!");
            return;
        }
        // 重新获取配置,已防缓存中的配置陈旧
        reSet();
        if (this.typeColumn == null)
        {
            if (tab.containsKey(key))
            {
                updateProperty(key, null, value);
            }
            else
            {
                insertProperty(key, null, value);
            }
        }
        else
        {
            if (type == null)
            {

                logger.error("修改配置失败:在key与type为联合主键的模式下type不能为空");
                return;
            }
            if (tab.containsKey(type + "|" + key))
            {
                updateProperty(key, type, value);
            }
            else
            {
                insertProperty(key, type, value);
            }
        }
    }

    /**
     * 将新增配置项添加到数据库中
     * @param key 需要保存的KEY
     * @param type 需要保存的KEY对应的类型
     * @param value 需要保存的值
     */
    private void insertProperty(String key, String type, String value)
    {

        StringBuffer query = new StringBuffer("INSERT INTO " + this.table);
        if (this.typeColumn != null)
        {
            query.append(" (" + this.typeColumn + ", " + this.keyColumn + ", " + this.valueColumn
                    + ") VALUES (?, ?, ?)");
        }
        else
        {
            query.append(" (" + this.keyColumn + ", " + this.valueColumn + ") VALUES (?, ?)");
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        try
        {
            conn = getConnection();

            logger.debug(" insertProperty query :" + query.toString());
            pstmt = conn.prepareStatement(query.toString());
            int index = 1;
            if (this.typeColumn != null)
            {
                pstmt.setString(index++, type);
            }
            pstmt.setString(index++, key);
            pstmt.setString(index++, value);
            // 将新增项加入到数据库中
            pstmt.executeUpdate();

            // 将新增项加入到缓存中
            if (this.typeColumn == null)
            {
                tab.put(key, value);
            }
            else
            {
                tab.put(type + "|" + key, value);
            }
        }
        catch (SQLException e)
        {

            logger.error("新增配置失败:key:" + key + ";type:" + type + ";value:" + value);
        }
        finally
        {
            close(conn, pstmt, null);
        }
    }

    /**
     * 修改已有配置项的value
     *
     * @param key 需要保存的KEY
     * @param type 需要保存的KEY对应的类型
     * @param value 需要保存的值
     */
    private void updateProperty(String key, String type, String value)
    {

        StringBuffer query = new StringBuffer("UPDATE " + this.table + " SET ");
        if (this.typeColumn == null)
        {
            query.append(this.valueColumn + " = ? WHERE " + this.keyColumn + " = ? ");
        }
        else
        {
            query.append(this.valueColumn + " = ? WHERE " + this.keyColumn + " = ? AND " + this.typeColumn + " = ? ");
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        try
        {
            conn = getConnection();

            logger.debug(" updateProperty query :" + query.toString());
            pstmt = conn.prepareStatement(query.toString());
            int index = 1;
            pstmt.setString(index++, value);
            pstmt.setString(index++, key);
            if (this.typeColumn != null)
            {
                pstmt.setString(index++, type);
            }
            // 将修改项更新到数据库中
            pstmt.executeUpdate();

            // 将修改项更新到缓存中
            if (this.typeColumn == null)
            {
                tab.put(key, value);
            }
            else
            {
                tab.put(type + "|" + key, value);
            }
        }
        catch (SQLException e)
        {

            logger.error("修改配置失败:key:" + key + ";type:" + type + ";value:" + value);
        }
        finally
        {
            close(conn, pstmt, null);
        }
    }

    /**
     * 读取配置表,加载到本地缓存
     */
    private void readConfig()
    {

        if (this.tab == null)
        {
            this.tab = new Hashtable<String, String>();
        }

        // 生成查询语句
        StringBuffer query = null;
        if (this.typeColumn == null)
        {
            // 以keyColumn为主键时
            query = new StringBuffer("SELECT " + this.keyColumn + "," + this.valueColumn + " FROM " + this.table);
        }
        else
        {
            // 以keyColumn与typeColumn为共同主键时
            query = new StringBuffer("SELECT " + this.typeColumn + "," + this.keyColumn + "," + this.valueColumn
                    + " FROM " + this.table);
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try
        {
            conn = getConnection();

            logger.debug(" readConfig sql :" + query.toString());
            pstmt = conn.prepareStatement(query.toString());
            rs = pstmt.executeQuery();
            while (rs.next())
            {
                if (this.typeColumn == null)
                {
                    // 以keyColumn为主键时
                    this.tab.put(rs.getString(1), rs.getString(2));
                }
                else
                {
                    // 以keyColumn与typeColumn为共同主键时
                    this.tab.put(rs.getString(1) + "|" + rs.getString(2), rs.getString(3));
                }
            }
        }
        catch (SQLException e)
        {

            logger.error("加载配置信息失败");
        }
        finally
        {
            close(conn, pstmt, rs);
        }
    }

    /**
     * 获取数据库连接
     * @return 数据库连接
     */
    private synchronized Connection getConnection()
    {

        Connection con = null;
        try
        {
            Class.forName(this.DB_PARAM[0]);
        }
        catch (Exception e)
        {

            logger.error("加载数据库驱动信息异常 ");
        }
        try
        {
            con = DriverManager.getConnection(this.DB_PARAM[1], this.DB_PARAM[2], this.DB_PARAM[3]);
        }
        catch (SQLException e)
        {

            logger.error("始初化数据库连接信息异常 ");
        }
        return con;
    }

    /**
     * 关闭相关数据库连接资源
     * @param conn
     * @param stmt
     */
    private void close(Connection conn, Statement stmt, ResultSet rs)
    {

        try
        {
            if (rs != null)
            {
                rs.close();
            }
        }
        catch (SQLException e)
        {
        }

        try
        {
            if (stmt != null)
            {
                stmt.close();
            }
        }
        catch (SQLException e)
        {
        }

        try
        {
            if (conn != null)
            {
                conn.close();
            }
        }
        catch (SQLException e)
        {
        }
    }

}


SystemInitiator
/**
 *
 */
package com.companyname.dhm.common.init;

import javax.servlet.ServletContext;

/**
 * @author
 *
 */
public class SystemInitiator
{
    static private SystemInfo systemInfo = null;

    static public SystemInfo getSystemInfo()
    {
        return systemInfo;
    }

    public static void setSystemInfo(SystemInfo systemInfo)
    {

        SystemInitiator.systemInfo = systemInfo;
    }

    public static void initApp(ServletContext ctx)
    {
        // get file seperator
        String FS = System.getProperty("file.separator");

        // get system name configed in web.xml
        String systemName = ctx.getInitParameter("dhm-system-name");

        // get working dir
        String work_dir = System.getProperty("user.dir");

        // set conf path
        String confPath = work_dir + FS + systemName + FS + ctx.getInitParameter("system.config-path-name");

        // set log path
        String logPath = work_dir + FS + systemName + FS + ctx.getInitParameter("system.log-path-name");

        systemInfo = new SystemInfo(systemName, confPath, logPath);
        System.out.println(systemInfo.toString());
    }
}

SystemInfo
package com.companyname.dhm.common.init;

/**
 * @author
 *
 */
public class SystemInfo
{
    private String systemName = null;
    private String confPath = null;
    private String logPath = null;

    public SystemInfo(String systemName, String confPath, String logPath)
    {
        this.systemName = systemName;
        this.confPath = confPath;
        this.logPath = logPath;
    }

    public String getSystemName()
    {
        return systemName;
    }

    public String getConfPath()
    {
        return confPath;
    }

    public String getLogPath()
    {
        return logPath;
    }

    public String toString()
    {
        return this.getClass().getName() + "[systemName=" + this.getSystemName() + ";confPath=" + this.getConfPath()
                + ";logPath=" + this.getLogPath() + "]";
    }
}

sysConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<config>
    <properties>
        <filepath>service/serErrorCode_zh_CN.properties</filepath>
        <filepath>system.properties</filepath>
    </properties>
    <xml>
        <filepath>sysConfig.xml</filepath>
    </xml>
</config>

    <context-param>
        <param-name>config.system-config-file</param-name>
        <param-value>sysConfig.xml</param-value>
    </context-param>
   

0 0
原创粉丝点击