当我们的业务代码要读取配置文件里的信息的时候,一般需要写个 SystemConfig类 来帮助我们,

下面我们就一起来写一个。

1、读取项目里的 system.properties 配置文件的时候,类似这样的文件

业务侧读取配置文件信息

我们这样写:

public class SystemConfig {

    private static Properties prop = new Properties();

    static {
        InputStream in = null;
        try {
            in = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("system.properties");
            prop.load(in);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally{
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     *
     * @param key
     * @return
     */
    public static String get(String key) {
        String str = prop.getProperty(key);
        if (StringUtils.isEmpty(str) || StringUtils.isEmpty(str.trim())) {
            return "";
        }
        return str.trim();
    }
}

当业务侧用到时,SystemConfig.get("A"),就行。

2、如果项目要做 代码配置 分离的话,解释一下啊,配置文件统一放在服务器的某一个位置(开发,测试,生产都是一个路径),比如 /home/webadmin/system.properties,

项目打包的时候和配置没关系,说白了就是一次打包,到处运行。

就把上面的 static 静态代码块 换成

static {
      //  File f = new File("/home/webadminconfig/system.properties");
        File f = new File("c:\\system.properties");
        try (InputStream in = new BufferedInputStream(new FileInputStream(f))) {
            prop.load(in);
        } catch (Exception e) {
            throw new RuntimeException("获取配置文件有误");
        }
    }
这里包括 读取本地和服务器的,一样的写法。哦对了,还有一点是,下面这个是 try-with-resources写法,我们不用再关闭流了。


相关文章: