天天看點

ResourceBundle擷取項目配置資訊

通常,項目的配置資訊都是放在.properties的檔案中。但是,我們怎麼擷取此配置檔案中的配置。

import java.util.Locale;

import java.util.MissingResourceException;

import java.util.ResourceBundle;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.springframework.context.i18n.LocaleContextHolder;

public class CustFeaturesConfig {

    protected final Log log = LogFactory.getLog(CustFeaturesConfig.class);

    private static CustFeaturesConfig config = null;

    private ResourceBundle rb;

    private CustFeaturesConfig() {

        Locale locale = LocaleContextHolder.getLocale();

        this.rb = ResourceBundle.getBundle("custfeatures", locale);

    }

    public static CustFeaturesConfig getInstance() {

        if (config == null) {

            config = new CustFeaturesConfig();

        }

        return config;

    }

    public Integer getIntegerConfig(String key) {

        return Integer.valueOf(getConfig(key));

    }

    public Long getLongConfig(String key) {

        return Long.valueOf(getConfig(key));

    }

    public String getConfig(String key) {

        String config;

        try {

            config = this.rb.getString(key);

        } catch (MissingResourceException mse) {

            config = "";

            this.log.info(key + "未找到!");

        }

        return config;

    }

    public void dispose() {

        config = null;

        this.rb = null;

    }

}

繼續閱讀