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");
            }
        }
    }
}


sev7e0
1 声望1 粉丝