Spring读取jar包外部的配置文件properties

一 。 如何获取jar包外的文件?

新项目用jar包运行,直接需求就是读取jar外部的配置文件properties,做到不同的环境有不同的配置信息。

用Spring管理的话

<context:property-placeholder ignore-unresolvable="true"
                              location="
                              classpath:config/database.properties,
                              classpath:config/voiceapi.properties,
                              classpath:config/threadpool.properties,
                              file:${user.dir}/override.properties"/>

需要2点:

1.file:协议 

2.${user.dir} ,来自jdk的 System.getProperty("user.dir") ,会输出项目的本地路径

二。 如何文件流?

public static String getProperties(String keyWord) {
    InputStream is = PropertiesProvider.class.getClassLoader().getResourceAsStream("config/error.properties");
    BufferedReader br = new BufferedReader(new InputStreamReader(is,Charset.forName("utf-8")));
    Properties properties = new Properties();
    try {
        properties.load(br);
        return properties.getProperty(keyWord);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

最合理的代码。推荐使用。如果用file 取读,会遇到jar包路径获取不到的问题。

三。如何获取文件路径?

当项目里需要读取配置文件,有相对路径和绝对路径之分。绝对路径存在无法迁移,适配性不高的问题,只讨论相对路径

java不会支持获取.java文件的路径,只能依靠根据.class文件获取相对路径

Producer.class.getResource("config/kafka.properties").getPath();

1.配置文件肯定需要统一管理, 通常在resource文件下

2.配置pom.xml,让maven打包的时候加入resource目录

<!--管理配置文件打包-->
<resources>
   <resource>
      <!--需要打包的目录-->
      <directory>${basedir}/src/main/resources</directory>
      <!--打包后的目录,默认是根目录-->
      <!--<targetPath>src/main/resources</targetPath>-->
      <filtering>false</filtering>
   </resource>
</resources>

3.程序里

static {
    properties = new Properties();
    String path = Producer.class.getResource("/config/kafka.properties").getPath();
    try {
        FileInputStream fis = new FileInputStream(new File(path));
        properties.load(fis);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

getResource方法的逻辑,如果是斜杠 / 符号开头,就是根目录找,这里和pom.xml的配置对应。

猜你喜欢

转载自my.oschina.net/u/2382040/blog/2050088