基于Xml 的IOC 容器-解析配置文件路径
生活随笔
收集整理的這篇文章主要介紹了
基于Xml 的IOC 容器-解析配置文件路径
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
XmlBeanDefinitionReader 通過調用ClassPathXmlApplicationContext 的父類DefaultResourceLoader 的getResource()方法獲取要加載的資源,其源碼如下
//獲取Resource的具體實現方法 @Override public Resource getResource(String location) {Assert.notNull(location, "Location must not be null");for (ProtocolResolver protocolResolver : this.protocolResolvers) {Resource resource = protocolResolver.resolve(location, this);if (resource != null) {return resource;}}//如果是類路徑的方式,那需要使用ClassPathResource 來得到bean 文件的資源對象if (location.startsWith("/")) {return getResourceByPath(location);}else if (location.startsWith(CLASSPATH_URL_PREFIX)) {return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());}else {try {// Try to parse the location as a URL...// 如果是URL 方式,使用UrlResource 作為bean 文件的資源對象URL url = new URL(location);return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));}catch (MalformedURLException ex) {// No URL -> resolve as resource path.//如果既不是classpath標識,又不是URL標識的Resource定位,則調用//容器本身的getResourceByPath方法獲取Resourcereturn getResourceByPath(location);}} }DefaultResourceLoader 提供了getResourceByPath()方法的實現,就是為了處理既不是classpath標識,又不是URL 標識的Resource 定位這種情況。
protected Resource getResourceByPath(String path) {return new ClassPathContextResource(path, getClassLoader()); }在ClassPathResource 中完成了對整個路徑的解析。這樣,就可以從類路徑上對IOC 配置文件進行加載,當然我們可以按照這個邏輯從任何地方加載,在Spring 中我們看到它提供的各種資源抽象,比如ClassPathResource、URLResource、FileSystemResource 等來供我們使用。上面我們看到的是定位Resource 的一個過程,而這只是加載過程的一部分。例如FileSystemXmlApplication 容器就重寫了getResourceByPath()方法:
@Override protected Resource getResourceByPath(String path) {if (path.startsWith("/")) {path = path.substring(1);}//這里使用文件系統資源對象來定義bean 文件return new FileSystemResource(path); }通過子類的覆蓋,巧妙地完成了將類路徑變為文件路徑的轉換。
?
總結
以上是生活随笔為你收集整理的基于Xml 的IOC 容器-解析配置文件路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于Xml 的IOC 容器-分配路径处理
- 下一篇: 销毁Bean的基本操作有哪些?