java的世界離不開資源設定檔,像spring架構等都非常依賴資源設定檔,而且spring也封裝了resource類,來處理資源檔的載入,這裡就不仔細分析spring載入資源檔了,主要分析下java 的ResourceBundle類載入資源設定檔。
其實分析了一下這個類的實現,其原理和spring一樣,都是利用ClassLoader讀取系統資源(SystemResource)檔案。
ResourceBundle bundle = ResourceBundle.getBundle(propFile, Locale.ENGLISH);
這個是統一的資源載入方式,屬性檔案的載入由
System.out.println(bundle.getClass());// class java.util.PropertyResourceBundle
java.util.PropertyResourceBundle這個實作類別實現的,這個實作類別主要讀取資源(從指定檔案),負載檔案到
java.util.Properties。
讀取負載檔案內容的關鍵代碼:
@SuppressWarnings({"unchecked", "rawtypes"}) public PropertyResourceBundle (InputStream stream) throws IOException { Properties properties = new Properties(); properties.load(stream); lookup = new HashMap(properties); }
@SuppressWarnings({"unchecked", "rawtypes"}) public PropertyResourceBundle (Reader reader) throws IOException { Properties properties = new Properties(); properties.load(reader); lookup = new HashMap(properties); }
不過定位資源檔的操作還是要看抽象類別ResourceBundle的代碼:
/** * A wrapper of ClassLoader.getSystemClassLoader(). */ private static class RBClassLoader extends ClassLoader { private static final RBClassLoader INSTANCE = AccessController.doPrivileged( new PrivilegedAction<RBClassLoader>() { public RBClassLoader run() { return new RBClassLoader(); } }); private static final ClassLoader loader = ClassLoader.getSystemClassLoader(); private RBClassLoader() { } public Class<?> loadClass(String name) throws ClassNotFoundException { if (loader != null) { return loader.loadClass(name); } return Class.forName(name); } public URL getResource(String name) { if (loader != null) { return loader.getResource(name); } return ClassLoader.getSystemResource(name); } public InputStream getResourceAsStream(String name) { if (loader != null) { return loader.getResourceAsStream(name); } return ClassLoader.getSystemResourceAsStream(name); } }
定位資源檔載入資源的關鍵是
getResource
<pre name="code" class="java">getResourceAsStream
這些方法。