Java commons-configuration.jarを使用してプロファイルを動的に変更(.properties)

2747 ワード

import java.util.Map;

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


/**
 * 
 *     properties     
 * @author lyh
 * @version 2012-6-5
 * @see PropertiesAutoLoad
 * @since
 */
public class PropertiesAutoLoad
{
    /**
     *   
     */
    private static final Logger log = Logger.getLogger(PropertiesAutoLoad.class);

    /**
     * Singleton
     */
    private static final PropertiesAutoLoad AUTO_LOAD = new PropertiesAutoLoad();

    /**
     * Configuration
     */
    private static PropertiesConfiguration propConfig;

    /**
     *     
     */
    private static boolean autoSave = true;

    /**
     * properties    
     * @param propertiesFile
     * @return 
     * @see
     */
    public static PropertiesAutoLoad getInstance(String propertiesFile)
    {
        //     
        init(propertiesFile);

        return AUTO_LOAD;
    }

    /**
     *   Key     value
     * @param key
     * @return 
     * @see
     */
    public Object getValueFromPropFile(String key)
    {
        return propConfig.getProperty(key);
    }

    /**
     *      value  
     * @param key
     * @return 
     * @see
     */
    public String[] getArrayFromPropFile(String key)
    {
        return propConfig.getStringArray(key);
    }

    /**
     *     
     * @param key
     * @param value 
     * @see
     */
    public void setProperty(String key, String value)
    {
        propConfig.setProperty(key, value);
    }

    /**
     *     
     * @param map 
     * @see
     */
    public void setProperty(Map map)
    {
        for (String key : map.keySet())
        {
            propConfig.setProperty(key, map.get(key));
        }
    }

    /**
     *       
     */
    private PropertiesAutoLoad()
    {

    }

    /**
     *    
     * @param propertiesFile 
     * @see
     */
    private static void init(String propertiesFile)
    {
        try
        {
            propConfig = new PropertiesConfiguration(propertiesFile);

            //      
            propConfig.setReloadingStrategy(new FileChangedReloadingStrategy());

            //    
            propConfig.setAutoSave(autoSave);
        }
        catch (ConfigurationException e)
        {
            log.error(e.getMessage());
        }
    }

    /**
     * Test
     * @param args 
     * @see
     */
    public static void main(String[] args)
    {
        log.info(PropertiesAutoLoad.getInstance("props/config/XX.properties").getValueFromPropFile(
            "pageSize"));
    }

}