PathMatchingResourcePatternResolver可以用來解析資源文件,主要是用來解析類路徑下的資源文件。當然它也可以用來解析其它資源文件,如基於文件系統的本地資源文件。PathMatchingResourcePatternResolver在使用時,可以直接new一個對象,new的時候可以通過使用帶ResourceLoader參數的構造方法,指定需要使用的ResourceLoader,解析好了資源后獲取資源時需要通過ResourceLoader獲取。PathMatchingResourcePatternResolver其實也是實現了ResourceLoader接口的。空的構造方法,將使用DefaultResourceLoader獲取資源。大多數時候我們直接使用其空構造函數即可。以下是一些PathMatchingResourcePatternResolver的使用示例。
獲取文件系統文件
獲取文件系統文件時,需要指定file前綴或者指定一個文件的絕對地址。如下示例就是取當前用戶路徑下的pom.xml文件的示例,這里用的是一個相對路徑,也可以把它改成一個絕對路徑。不加資源協議時,會從類路徑下去找對應的文件。
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); resource = resolver.getResource("file:pom.xml"); Assert.assertNotNull(resource); Assert.assertNotNull(resource.getInputStream());
從類路徑下獲取指定的文件
從類的根路徑下獲取applicationContext.xml文件
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //從classpath下獲取單個的資源文件,classpath下沒有將嘗試把資源當做一個UrlResource Resource resource = resolver.getResource("applicationContext.xml"); Assert.assertNotNull(resource); Assert.assertNotNull(resource.getInputStream());
如果不是根路徑,需要指定路徑,比如下面就是從類路徑的META-INF/spring目錄下獲取applicationContext.xml文件。
Resource resource = resolver.getResource("META-INF/spring/applicationContext.xml");
可以明確的指定classpath前綴
Resource resource = resolver.getResource("classpath:META-INF/spring/applicationContext.xml");
獲取所有類路徑下的指定文件
可以通過classpath*前綴指定,從所有的類路徑下獲取指定的文件,與classpath前綴的區別是classpath前綴只能獲取當前類路徑下的資源文件,而classpath*前綴可以獲取所有類路徑下的資源文件,包括jar包中的。以下示例就是從所有類路徑下獲取META-INF/spring目錄下的applicationContext.xml文件。
Resource[] resources = resolver.getResources("classpath*:META-INF/spring/applicationContext.xml"); Assert.assertNotNull(resources); Assert.assertTrue(resources.length == 1);
使用通配符獲取滿足某種格式的文件
在解析文件時可以通過*表示匹配所有的字符,比如下面的示例將匹配類的根路徑下的所有的以applicationContext開頭的xml文件。
Resource[] resources = resolver.getResources("classpath*:applicationContext*.xml"); Assert.assertNotNull(resources); //筆者的classpath下一共有三個滿足applicationContext*.xml的資源文件 Assert.assertTrue(resources.length == 3);
如果不是在根路徑下,也可以指定路徑。
Resource[] resources = resolver.getResources("classpath*:com/elim/learn/spring/applicationContext*.xml"); Assert.assertNotNull(resources); //筆者的classpath下一共有三個滿足applicationContext*.xml的資源文件 Assert.assertTrue(resources.length == 3);
假設我們的資源文件是按照模塊划分的,放在不同的目錄下面,比如com.elim.learn.spring路徑下有,com.elim2.learn.spring路徑下也有,那么我們可以把elim和elim2用*代替。
Resource[] resources = resolver.getResources("classpath*:com/*/learn/spring/applicationContext*.xml"); Assert.assertNotNull(resources); //com.elim.learn.spring和com.elim2.learn.spring下各有三個applicationContext*.xml形式的資源文件 Assert.assertTrue(resources.length == 6);
也可以用兩個*表示任意多層的目錄
Resource[] resources = resolver.getResources("classpath*:com/**/spring/applicationContext*.xml"); Assert.assertNotNull(resources); //com.elim.learn.spring和com.elim2.learn.spring下各有三個applicationContext*.xml形式的資源文件 Assert.assertTrue(resources.length == 6);
參考:
原文:https://blog.csdn.net/elim168/article/details/78197596