properties檔案載入器

sev7e0發表於2019-01-19
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Service
public class PropLoad {

    private static final Logger logger = LoggerFactory.getLogger(PropLoad.class);
    private static PropLoad instance = new PropLoad();
    private Properties props = new Properties();
    private PropLoad() {
    }
    
    public static synchronized String getProp(String key) {
        return instance.props.getProperty(key);
    }

    public static synchronized String getProp(String key, String defaultValue) {
        return instance.props.getProperty(key, defaultValue);
    }

    @PostConstruct
    public static void enter() {
        logger.debug("PropLoad init ...");
        instance.init();
        logger.debug("PropLoad init finish.");
    }

    private void init() {
        String path = "prop.properties";
        //InputStream in = ClassLoader.getSystemResourceAsStream(path);
        //為了解決在idea外,無法訪問資源目錄的問題
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);
        if (in == null){
            logger.error("file path error,please check");
        }
        try {
            props.load(in);
        } catch (IOException e) {
            logger.error("load prop.properties error {}",e.getMessage());
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("InputStream close error");
            }
        }
    }
}

相關文章