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

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

新項目用jar包運行,直接需求就是讀取jar外部的配置文件properties,作到不一樣的環境有不一樣的配置信息。api

用Spring管理的話maven

<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點:ide

1.file:協議 spa

2.${user.dir} ,來自jdk的 System.getProperty("user.dir") ,會輸出項目的本地路徑xml

 

二。 如何文件流?blog

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包路徑獲取不到的問題。utf-8

三。如何獲取文件路徑?get

當項目裏須要讀取配置文件,有相對路徑和絕對路徑之分。絕對路徑存在沒法遷移,適配性不高的問題,只討論相對路徑kafka

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的配置對應。

相關文章
相關標籤/搜索