手边星辰

博客园 首页 新随笔 联系 订阅 管理

http://www.tuicool.com/articles/NVza2am

枚举类也是懒加载的(lazy loading)

 

举个栗子:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropertiesUtil {
    
    private static class Inner {
        static{
            prop = fillProperty("/global.properties");
        }
        private static Properties prop;
    }

    private static Logger log = LoggerFactory.getLogger(PropertiesUtil.class);

    public static Properties fillProperty(String propName) {
        InputStream in = null;
        try {
            in = PropertiesUtil.class.getResourceAsStream(propName);
            Properties prop = new Properties();
            prop.load(in);
            return prop;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != in)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }

    public static String getProperty(String key) {
        if (null != Inner.prop) {
            return Inner.prop.getProperty(key);
        }
        log.debug(" init prop failed.");
        return null;
    }

    public static String getProperty(String fileName, String key) {
        if (null != fileName && fileName.trim().length() != 0) {
            Properties prop = fillProperty(fileName);
            if (null != prop) {
                return prop.getProperty(key);
            }
            log.debug("can not find the file:" + fileName);
        }
        return null;
    }

}

 

posted on 2016-08-08 11:29  手边星辰  阅读(390)  评论(0编辑  收藏  举报