加載文件順序
情形一:使用classpath加載且不含通配符
這是最簡單的情形,Spring默認會使用當前線程的ClassLoader的getResource
方法獲取資源的
URL
,如果無法獲得當前線程的
ClassLoader
,
Spring
將使用加載類
org.springframework.util.ClassUtils的ClassLoader。
1.當工程目錄結構如圖所示:
ApplicationContext context = new ClassPathXmlApplicationContext("conf/application-context.xml");
加載[conf/application-context.xml]
2.當工程目錄結構如圖所示:
ApplicationContext context = new ClassPathXmlApplicationContext("conf/application-context.xml");
加載[conf/application-context.xml]
3. 當工程目錄結構如圖所示:
ApplicationContext context = new ClassPathXmlApplicationContext("conf/application-context.xml");
只會會加載bin/conf目錄下的application-context.xml文件,不會加載jar包中的conf/application-context.xml。
情形二:使用classpath加載,包含通配符
Spring會通過使用路徑中的非通配符部分先確定資源的大致位置,然后根據這個位置在確定具體的資源位置
ApplicationContext context = new ClassPathXmlApplicationContext("conf/**/*application-context.xml");
加載[admin-application-context.xml]
加載[application-context.xml]
2.當工程目錄結構如圖所示:
ApplicationContext context = new ClassPathXmlApplicationContext("conf/**/*application-context.xml");
加載conf/application-context.xml
加載conf/admin/admin-application-context.xml
3.當工程目錄結構如圖所示:
ApplicationContext context = new ClassPathXmlApplicationContext("conf/**/*application-context.xml");
bin/conf/application-context.xml文件和bin/conf/admin/admin-application-context.xml都會被加載,
但conf.jar文件中的配置文件並不會被加載。
情形三:使用classpath*前綴且不包含通配符
使用classpath*前綴可以獲取所有與給定路徑匹配的classpath資源,從而避免出現兩個不同位置有相同名字的文件,Spring只加載其中一個的情況。
這時使用
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:conf/application-context.xml");
Spring將會加載bin目錄下的application-context.xml文件和jar包里的application-context.xml文件。
情形四:使用classpath*前綴,包含通配符
當工程目錄結構如圖所示:
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:conf/**/*application-context.xml");
conf目錄下包括各級子目錄中的所有配置文件,因此bin/conf/application-context.xml和 bin/conf/admin/admin-application-context.xml
以及jar包中的 conf/application-context.xml和 conf/admin/admin-application-context.xml都會被加載
Classpath*加載和Classpath加載區別
classpath*:的出現是為了從classpath和多個jar文件中加載相同的文件,classpath:只能加載找到的第一個文件。
classpath*載使用了classloader的getResources() 方法;
PathMatchingResourcePatternResolver類中,我們可以更清楚的了解其對的處理:如果是以classpath*開頭,它會遍歷classpath。
最終從文件加載的時候仍然是JAVA中常見的讀取文件的方法:
如ClassPathResource得到inputstream的方法是利用class loader。
如ClassPathResource得到inputstream的方法是利用class loader。
public InputStream getInputStream() throws IOException { InputStream is; if (this.clazz != null) { is = this.clazz.getResourceAsStream(this.path); }
如FileSystemResource得到inputstream的方法是利用FileInputStream。
public InputStream getInputStream() throws IOException { return new FileInputStream(this.file); }