讀取配置文件

1. Spring 和 Apache Commons Configuration

   若是項目中沒什麼特殊的個性化讀取配置文件需求,能夠使用 Spring 管理配置文件信息,而後注入到須要的地方。java

   配置文件中須要添加(PS :多配置文件,添加 ignore-unresolvable 參數)。web

    <context:property-placeholder location="classpath:db-info.properties" ignore-unresolvable="true"/>

    <context:property-placeholder location="classpath:web.properties" ignore-unresolvable="true"/>

   而後再須要的地方spring

   動態讀入能夠使用 Spring 提供了默認的配置文件讀取實現類  org.springframework.core.io.DefaultResourceLoader。apache

   固然你也能夠實現  org.springframework.core.io.ResourceLoader 接口自定義配置文件載入實現類。編程

   org.springframework.core.io.DefaultResourceLoader 核心方法 getResource:設計模式

複製代碼

public Resource getResource(String location) {
        Assert.notNull(location, "Location must not be null");
        Iterator ex = this.protocolResolvers.iterator();
        Resource resource;        do {            if(!ex.hasNext()) {                if(location.startsWith("/")) {                    return this.getResourceByPath(location);
                }                if(location.startsWith("classpath:")) {                    return new ClassPathResource(location.substring("classpath:".length()), this.getClassLoader());
                }                try {
                    URL ex1 = new URL(location);                    return new UrlResource(ex1);
                } catch (MalformedURLException var5) {                    return this.getResourceByPath(location);
                }
            }
            ProtocolResolver protocolResolver = (ProtocolResolver)ex.next();
            resource = protocolResolver.resolve(location, this);
        } while(resource == null);        return resource;
    }

複製代碼

   能夠看出 Spring 能支持入參路徑的不少方式,包括已 " /"、"classpath" 開頭。 app

   若是你想在項目中使用 Spring 提供的默認配置文件載入實現,能夠這樣書寫你的代碼。框架

            ResourceLoader resourceLoader = = resourceLoader.getResource("log4j.properties"=

   固然你也能夠引入 Apache Commons Configuration jar 內部設計至關考究。ide

   整個 jar 不超過 400K,若是時間充裕,你也能夠反編譯看看源碼。工具

   使用方式也特別簡潔,兩行代碼就 OK:

  PropertiesConfiguration configuration  = new PropertiesConfiguration("log4j.properties");
  configuration.getString("log4j.appender.file");

   Apache Commons Configuration 默認載入配置文件核心實現類 org.apache.commons.configuration.AbstractFileConfiguration 載入方法:

複製代碼

    public void load(String fileName) throws ConfigurationException {        try {
            URL e = ConfigurationUtils.locate(this.fileSystem, this.basePath, fileName);            if(e == null) {                throw new ConfigurationException("Cannot locate configuration source " + fileName);
            } else {                this.load(e);
            }
        } catch (ConfigurationException var3) {            throw var3;
        } catch (Exception var4) {            throw new ConfigurationException("Unable to load the configuration file " + fileName, var4);
        }
    }

複製代碼

回到頂部

2. JDK 經典手寫

   若是你項目對讀取配置文件沒有太多個性化的需求,若是你有足夠時間,若是你嫌棄第三方 Jar 佔據你 lib 目錄的一席之地,還有若是你熱愛編程。

   仔細一點,你會發現,這些開源框架底層都是已 java.net.URL 載入配置文件。

   在載入配置文件的過程當中應項目需求採用了恰當的設計模式,使可以支持一些對配置文件的特定操做。

   載入文件後,實例化爲 java.util.Properties 對象,進行配置文件獲取。

   那就徹底能夠擼段純 JDK 的寫法,做爲工具類放入項目中,編譯後不超過 5K,核心的幾句代碼以下:

          URL resource = Thread.currentThread().getContextClassLoader().getResource("log4j.properties");
          Properties properties = new Properties();
          properties.load(resource.openStream());          properties.getProperty(key);

  由於  java.util.Properties 的 load 進行了方法的重載,你也能夠不用 URL 方式讀取配置文件,也能夠這樣寫:

          String url = XXXXX.class.getResource("").getPath().replaceAll("%20", " ");
          String path = url.substring(0, url.indexOf("classes")) + filePath; //該 path 爲你配置文件的路徑

          InputStream inputStream = new FileInputStream(path);
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
          prop.load(bufferedReader);prop.getProperty(key);

 上述代碼都爲實例核心的幾句代碼,其中的判空和異常都沒有進行處理,僅做爲參考。

 最後貼上本身封裝的配置文件載入類,不使用任何第三方 jar,有須要的拿走放入項目便可用。

 View Code

  使用方式也很簡單,支持多路徑讀入,若是存在相同 Key 後面的覆蓋前面的:

        PropertiesLoader propertiesLoader = new PropertiesLoader("log4j.properties");
        System.out.println(propertiesLoader.getProperty("log4j.appender.file"));
相關文章
相關標籤/搜索