讀取設定檔隨想,設定檔隨想

來源:互聯網
上載者:User

讀取設定檔隨想,設定檔隨想

   無論項目大小,資料庫、開發環境、測試環境....這些資訊,肯定不能在程式中寫入程式碼。

   寫入程式碼有百壞而無一利,每次資訊變動都要重新編譯項目,不能分離營運和開發。

   而且配置散落在項目的程式中,無法做到準確集中管理,拖慢項目進度。

   我想這也是設定檔出現的原因,設定檔比較主流的格式 properties(索引值對形式)、xml(對象,複雜資料結構,只有你想不到沒有xml 表達不了的) 等。

   本文已比較常見、簡單的 properties 格式的設定檔為例,來看看讀取設定檔幾種不同的姿勢,關注其中的實現和使用,設計模式另表。

1. Spring 和 Apache Commons Configuration

   Spring 提供了預設的設定檔讀取實作類別  org.springframework.core.io.DefaultResourceLoader。

   當然你也可以實現  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" 開頭。 

   如果你想在項目中使用 Spring 提供的預設設定檔載入實現,可以這樣書寫你的代碼。

            ResourceLoader resourceLoader = new DefaultResourceLoader();            Resource resource = resourceLoader.getResource("log4j.properties");            Properties props = new Properties();            props.load(resource.getInputStream());

   當然你也可以引入 Apache Commons Configuration jar 內部設計相當考究。

   整個 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,有需要的拿走放入項目即可用。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.