天天看點

簡說Spring中的資源加載

簡說Spring中的資源加載

聲明: 本文若有 任何纰漏、錯誤,請不吝指正!謝謝!

問題描述#

遇到一個關于資源加載的問題,是以簡單的記錄一下,對Spring資源加載也做一個記錄。

問題起因是使用了@PropertySource來進行配置檔案加載,配置路徑時,沒有使用關鍵字classpath來指明從classpath下面來查找配置檔案。具體配置如下

Copy

@PropertySource("config/application-download.yml", factory=YamlPropertySourceFactory)

這種方式在啟動應用時,是沒問題的,正常。但是在build時,跑單元測試,出了問題,說無法從ServletContext中找到/config/application-download.yml,然後加上了classpath,再跑了下就沒錯誤了。

于是找到了處理@PropertySource的位置,跟蹤代碼找到了差異的原因。

源碼解釋#

Spring對于資源,做了一個抽象,那就是Resource,資源的加載使用資源加載器來進行加載,ResourceLoader就是這樣一個接口,用于定義對資源的加載行為的。

Spring中幾乎所有的ApplicationContext都實作了它,應用十分的廣泛。

除了各個ApplicationContext實作了它,它還有個可以獨立使用的實作,也就是一會要提到的。

DefaultResourceLoader#

這個實作類,是一個在架構外部獨立使用版本,一般預設的都不簡單 ,這個也不例外。

無論從哪裡加載資源,使用DefaultResourceLoader來加載就行了

// org.springframework.core.io.DefaultResourceLoader#getResource

@Override

public Resource getResource(String location) {

Assert.notNull(location, "Location must not be null");

// 這個是提供的SPI使用的,沒有采用子類實作的方式

for (ProtocolResolver protocolResolver : getProtocolResolvers()) {

Resource resource = protocolResolver.resolve(location, this);
  if (resource != null) {
     return resource;
  }           

}

// 如果以/開頭,使用純路徑的方式,比如./config.properties

if (location.startsWith("/")) {

return getResourceByPath(location);           

// 如果以classpath:開頭,建立一個ClassPathResource資源對象

// 底層使用的是Class#getResourceAsStream,ClassLoader#getResourceAsStream

// 或者 ClassLoader#getSystemResourceAsStream,具體有機會再詳細解釋下這些

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...
     // 如果上面的判斷不滿足,直接使用java.net.URL來生成一個URL對象,
     // 如果location為null,或者location沒有指定協定,或者協定不能被識别
     // 就會抛出異常
     URL url = new URL(location);
     //file:開頭的 會使用建立一個FileUrlResource
     return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
  }
  catch (MalformedURLException ex) {
     // 沒有指定協定
     return getResourceByPath(location);
  }           

protected Resource getResourceByPath(String path) {

// ClassPathResource的子類
return new ClassPathContextResource(path, getClassLoader());           

這個類在Spring中被廣泛使用,或者更具體的說,這個類的getResource方法,幾乎遇到資源相關的加載動作都會調用到它。

各個ApplicationContext應該是加載資源最多的地方了,而AbstractApplicationContext正是繼承了DefaultResourceLoader,才有了這中加載資源的能力。

不過DefaultResourceLoader也留給了子類的擴充點,主要是通過重寫getResourceByPath這個方法。這裡是繼承的方式,也可以重寫 getResource方法,這個方法在GenericApplicationContext中被重寫了, 不過也沒有做過多的操作,這裡主要是可以在一個context中設定自己的資源加載器,一旦設定了,會将 ApplicationContext中所有的資源委托給它加載,一般不會有這個操作 。

遇到的問題 ,正是因為子類對 getResourceByPath的重寫 ,導緻了不一樣的行為。

經過跟蹤源碼發現,正常啟動應用的時候,執行個體化的是一個 AnnotationConfigServletWebServerApplicationContext執行個體 ,這個類繼承自ServletWebServerApplicationContext,在ServletWebServerApplicationContext中重寫了getResourceByPath

// org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#getResourceByPath

if (getServletContext() == null) {

// ServletContext為null,從classpath去查找
  return new ClassPathContextResource(path, getClassLoader());           

// 否則從ServletContext去查找

return new ServletContextResource(getServletContext(), path);

而通過 Debug發現,在使用SpirngBootTest執行單元測試,它執行個體化的是org.springframework.web.context.support.GenericWebApplicationContext

/**

  • This implementation supports file paths beneath the root of the ServletContext.
  • @see ServletContextResource
  • 這裡就是直接從ServletContext中去查找資源,一般就是webapp目錄下。

    */

Assert.state(this.servletContext != null, "No ServletContext available");

return new ServletContextResource(this.servletContext, path);

并且這裡ServletContext不為null,SpringBootTest執行個體化一個SpringBootMockServletContext對象。

而正常情況下,在處理@PropertySource時,還沒能初始化一個ServletContext,因為 @PropertySource的處理是在BeanDefinitionRegistryPostProcessor執行時處理的,早于SpringBoot去初始化Servlet容器。SpringBoot建立Servlet容器是在這裡org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#onRefresh,它的執行時機是晚于處理 BeanFactoryPostProcessor的org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors,是以 正常運作應用,肯定隻會建立一個ClassPathContextResource資源對象,而配置檔案在classpath下是存在的,是以可以搜尋到。

結論#

結論就是不知道SpringBootTest是故意為之呢還是出于什麼别的考慮,也不知道除了加上classpath字首外是否有别的方式能解決這個問題。

不過現在看來,偷懶是不可能的呢了 ,老老實實的 把字首classpath給加上,就不會有問題了

作者: 早知今日

出處:

https://www.cnblogs.com/heartlake/p/12974265.html