Dashboard > OpenSource Project > ... > Spring > 入門 14 - 資源檔案的取得
OpenSource Project Log In   View a printable version of the current page.
入門 14 - 資源檔案的取得
Added by 良葛格, last edited by 良葛格 on Nov 27, 2004  (view change)
Labels: 
(None)

 首先來看看ApplicationContext介面的實作,之前我們使用了ClassPathXmlApplicationContext,這會讀取CLASSPATH根目錄(加上指定路徑)中可獲取的資源檔案。

 我們也可以使用FileSystemXmllApplicationContext,這會使用相對於工作根目錄的檔案路徑來取得資源檔案,例如若您的工作目錄是"c:\workspace\springtest\",而您在程式中指定了"bean.xml",則程式會至您的"c:\workspace\ springtest\bean.xml"找您指定的資源檔案,同理,若您指定了"conf\somepro.properties",則會至"c:\ workspace\springtest\conf\somepro.properties"中找您指定的檔案。

 對於Web應用程式來說,您可以使用XmlWebApplicationContext,這會以您的Web應用程式作為相對路徑的起點,例如若指定"WEB-INF\conf\admin.properties",而您的Web應用程式是springweb,則會至"springweb\WEB- INF\conf\admin.properties"找您的檔案。

 Spring提供了對資源檔案的泛型存取(generic access),而這正是一個好的應用程式在存取資源檔案時最重要的特性,除了上面的方案之外,ApplicationContext繼承了 ResourceLoader介面,您可以使用getResource()方法並指定資源檔案的url來取得一個實作Resource介面的實例,例如:

Resource resource = context.getResource("classpath:admin.properties");

 "classpath:"是Spring自訂的url虛擬協定,這會取回一個 org.springframework.core.io.ClassPathResource實例,資源檔案是位於CLASSPATH根目錄中,您也可以指定標準的url,像是"file:"或"http:",例如:

Resource resource = context.getResource("file:c:/workspace/springtest/conf/admin.properties");

 這會返回一個org.springframework.core.io.FileSystemResource實例,或者您可以如下指定來返回一個ServletContextResource實例:

Resource resource = context.getResource("WEB-INF/conf/admin.properties");

 取得一個實作Resource介面的實例之後,您可以使用getFile()、getInputStream()等方式來操作或取得資源檔案的相關資源,Resource介面的實例只是資源檔案的一個抽象代表,指指定的資源檔案實際上可能並不存在,您可以使用exists()方法來進行測試。

Site powered by a free Open Source Project / Non-profit License (more) of Confluence - the Enterprise wiki.
Learn more or evaluate Confluence for your organisation.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.1.5a Build:#411 Mar 16, 2006) - Bug/feature request - Contact Administrators