Resource
?當咱們學習Spring時,咱們總會在xml中對bean進行聲明,而後再經過下面的代碼片斷來獲取bean。代碼以下:spring
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Context {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring.xml");//一、加載配置文件
System.err.println(ctx.getBean("stu").toString());//二、經過配置文件獲取一個bean並打印
}
}
複製代碼
上面第一行代碼加載了一個資源文件Spring.xml
,這個資源文件在Spring中屬於Resource
的一種。這樣講,Spring把各類類型的文件,二進制流都稱之爲Resource
,只不過對於Spring開發者來講,Resource
大多都是xml文件。bash
Resource是一個接口,接口裏邊定義了很是多關於文件的操做策略
,好比學習
exists():判斷資源是否存在
getURL():獲取資源的URL
getFilename():獲取資源的名稱
......(方法很是多,我就不一一列舉了)
Resource
接口是具體資源訪問策略的抽象,也是全部資源訪問類所實現的接口。Resource
接口自己沒有提供訪問任何底層資源的實現邏輯,針對不一樣的底層資源,Spring 將會提供不一樣的 Resource
實現類,不一樣的實現類負責不一樣的資源訪問邏輯。spa
很是重要的一點,這也是Spring Resource設計最美妙的地方,那就是Spring 在Resource資源處理上採用啦策略模式
,這也是我爲何上面把Resource接口中的方法稱之爲策略
的緣由了!設計
若是還不瞭解Java 策略模式
的朋友請先自行學習!code
Spring Resource
接口類結構圖爲了更好地理解,在這裏我先放一張策略模式
的UML圖,它的具體內容本文不講。cdn
好了!圖片放上去了,那麼策略模式
在Resource
體系上如何體現出來呢?xml
Resource
接口至關於咱們的策略
AbstractResource
在內都屬於咱們的具體策略實現
context
角色到哪裏去了呢?哈哈,作生意不能忘了咱們的老本啊!它就是咱們的IOC容器ApplicationContext
,它是咱們策略模式中最最最具備決策能力的老大了至於爲何容器就能夠處理咱們的Resource
,我接下去會說到!blog
很明顯,Resource
是資源的最高抽象,一般咱們的應用程序不是都從classpath
下去加載咱們的xml文件,咱們也能夠經過一個URL
,URI
,InputStream
等方式獲取一個資源,這就是Spring把資源的獲取方式和資源的定義之間解耦了!接口
ResourceLoader
接口ResourceLoader
:該接口實現類的實例能夠得到一個 Resource 實例。。在 ResourceLoader
接口裏有以下方法:
Resource getResource(String location)
:該接口僅包含這個方法,該方法用於返回一個 Resource
實例。ApplicationContext
的實現類都實現 ResourceLoader
接口,而該接口又返回一個Resource
實例,所以 ApplicationContext
可用於直接獲取 Resource
實例,這也是爲何容器就能夠處理Resource
的緣由!
策略模式
在Spring中使用有什麼優點當 Spring
應用須要進行資源訪問時,實際上並不須要直接使用 Resource
實現類,而是調用 ApplicationContext
實例的 getResource()
方法來得到資源,ApplicationContext
將會負責選擇 Resource
的實現類,也就是肯定具體的資源訪問策略,從而將應用程序和具體的資源訪問策略分離開來。
既然有那麼多的優點,下面就在來解釋咱們上面的第一段代碼,爲何要使用ClassPathXmlApplicationContext
這個類來對資源進行加載?
咱們都知道,在容器ApplicationContext
下有不少的實現,好比FileSystemXmlApplicationContext
,ClassPathXmlApplicationContext
,XmlWebApplicationContext
,並且咱們加載配置文件的方式一般也是使用它們來進行加載,在Spring中,ApplicationContext
的實現類顧名思義也是對應了咱們Resource
接口的一些實現策略,好比ClassPathResource
,FileSystemResource
等。