在日常程序開發中,處理外部資源是很繁瑣的事情,我們可能需要處理URL資源、File資源資源、ClassPath相關資源、服務器相關資源(JBoss AS 5.x上的VFS資源)等等很多資源。因此處理這些資源需要使用不同的接口,這就增加了我們系統的複雜性;而且處理這些資源步驟都是類似的(打開資源、讀取資源、關閉資源),因此如果能抽象出一個統一的接口來對這些底層資源進行統一訪問,是不是很方便,而且使我們系統更加簡潔,都是對不同的底層資源使用同一個接口進行訪問。
Spring 提供一個Resource接口來統一這些底層資源一致的訪問,而且提供了一些便利的接口,從而能提供我們的生產力。
Resource實體類
Resource 結構圖
UrlResource(訪問網絡資源)
UrlResource代表URL資源,用於簡化URL資源訪問。“isOpen”永遠返回false,表示可多次讀取資源。
UrlResource一般支持如下資源訪問:
- http:通過標準的http協議訪問web資源,如new UrlResource(“http://地址”);
- ftp:通過ftp協議訪問資源,如new UrlResource(“ftp://地址”);
- file:通過file協議訪問本地文件系統資源,如new UrlResource(“file:d:/test.txt”);ClassPathResource(訪問類路徑資源)
ClassPathResource代表classpath路徑的資源,將使用ClassLoader進行加載資源。classpath 資源存在於類路徑中的文件系統中或jar包裏,且“isOpen”永遠返回false,表示可多次讀取資源。
ClassPathResource加載資源替代了Class類和ClassLoader類的“getResource(String name)”和“getResourceAsStream(String name)”兩個加載類路徑資源方法,提供一致的訪問方式。
使用默認的加載器加載資源,將加載當前ClassLoader類路徑上相對於根路徑的資源
@Test public void testClasspathResourceByDefaultClassLoader() throws IOException { Resource resource = new ClassPathResource("com/heqing/spring/test.properties"); if(resource.exists()) { dumpStream(resource); } System.out.println("path:" + resource.getFile().getAbsolutePath()); Assert.assertEquals(false, resource.isOpen()); }
使用指定的ClassLoader進行加載資源,將加載指定的ClassLoader類路徑上相對於根路徑的資源
@Test public void testClasspathResourceByClassLoader() throws IOException { ClassLoader cl = this.getClass().getClassLoader(); Resource resource = new ClassPathResource("com/heqing/spring/test.properties" , cl); if(resource.exists()) { dumpStream(resource); } System.out.println("path:" + resource.getFile().getAbsolutePath()); Assert.assertEquals(false, resource.isOpen()); }
使用指定的類進行加載資源,將嘗試加載相對於當前類的路徑的資源
@Test public void testClasspathResourceByClass() throws IOException { Class clazz = this.getClass(); Resource resource1 = new ClassPathResource("com/heqing/spring/test.properties" , clazz); if(resource1.exists()) { dumpStream(resource1); } System.out.println("path:" + resource1.getFile().getAbsolutePath()); Assert.assertEquals(false, resource1.isOpen()); Resource resource2 = new ClassPathResource("test1.properties" , this.getClass()); if(resource2.exists()) { dumpStream(resource2); } System.out.println("path:" + resource2.getFile().getAbsolutePath()); Assert.assertEquals(false, resource2.isOpen()); }
加載jar包裏的資源,首先在當前類路徑下找不到,最後纔到Jar包裏找,而且在第一個Jar包裏找到的將被返回
@Test public void classpathResourceTestFromJar() throws IOException { Resource resource = new ClassPathResource("overview.html"); if(resource.exists()) { dumpStream(resource); } System.out.println("path:" + resource.getURL().getPath()); Assert.assertEquals(false, resource.isOpen()); }
FileSystemResource(訪問文件系統資源)
FileSystemResource代表java.io.File資源,對於“getInputStream ”操作將返回底層文件的字節流,“isOpen”將永遠返回false,從而表示可多次讀取底層文件的字節流。
@Test public void testFileResource() { File file = new File("d:/test.txt"); Resource resource = new FileSystemResource(file); if(resource.exists()) { dumpStream(resource); } Assert.assertEquals(false, resource.isOpen()); }
ServletContextResource(訪問應用相關)
ServletContextResource代表web應用資源,用於簡化servlet容器的ServletContext接口的getResource操作和getResourceAsStream操作;
InputStreamResource(訪問字節數組資源)
InputStreamResource代表java.io.InputStream字節流,對於“getInputStream ”操作將直接返回該字節流,因此只能讀取一次該字節流,即“isOpen”永遠返回true。
@Test public void testInputStreamResource() { ByteArrayInputStream bis = new ByteArrayInputStream("Hello World!".getBytes()); Resource resource = new InputStreamResource(bis); if(resource.exists()) { dumpStream(resource); } Assert.assertEquals(true, resource.isOpen()); }
ByteArrayResource(訪問數組資源)
ByteArrayResource代表byte[]數組資源,對於“getInputStream”操作將返回一個ByteArrayInputStream。
@Test
public void testByteArrayResource() {
Resource resource = new ByteArrayResource("Hello World!".getBytes());
if(resource.exists()) {
dumpStream(resource);
}
}
ResourceLoader接口
ResourceLoader接口用於返回Resource對象;其實現可以看作是一個生產Resource的工廠類。
ResourceLoader在進行加載資源時需要使用前綴來指定需要加載:“classpath:path”表示返回ClasspathResource,“http://path”和“file:path”表示返回UrlResource資源,如果不加前綴則需要根據當前上下文來決定,DefaultResourceLoader默認實現可以加載classpath資源。
@Test public void testResourceLoad() { ResourceLoader loader = new DefaultResourceLoader(); Resource resource = loader.getResource("classpath:com.heqing/spring/test1.txt"); //驗證返回的是ClassPathResource Assert.assertEquals(ClassPathResource.class, resource.getClass()); Resource resource2 = loader.getResource("file:com.heqing/spring/test1.txt"); //驗證返回的是ClassPathResource Assert.assertEquals(UrlResource.class, resource2.getClass()); Resource resource3 = loader.getResource("com.heqing/spring/test1.txt"); //驗證返默認可以加載ClasspathResource Assert.assertTrue(resource3 instanceof ClassPathResource); }
- ClassPathXmlApplicationContext : 不指定前綴將返回默認的ClassPathResource資源,否則將根據前綴來加載資源;
- FileSystemXmlApplicationContext : 不指定前綴將返回FileSystemResource,否則將根據前綴來加載資源;
- WebApplicationContext : 不指定前綴將返回ServletContextResource,否則將根據前綴來加載資源;
- 其他 : 不指定前綴根據當前上下文返回Resource實現,否則將根據前綴來加載資源。
ResourceLoaderAware接口
ResourceLoaderAware是一個標記接口,用於通過ApplicationContext上下文注入ResourceLoader。
測試Bean,只需實現ResourceLoaderAware接口,然後通過回調將ResourceLoader保存
package com.heqing.spring.bean; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.io.ResourceLoader; public class ResourceBean implements ResourceLoaderAware { private ResourceLoader resourceLoader; @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public ResourceLoader getResourceLoader() { return resourceLoader; } }
配置Bean定義(chapter/resourceLoaderAware.xml):
<bean class="com.heqing.spring.bean.ResourceBean"/>
測試
@Test public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("chapter/resourceLoaderAware.xml"); ResourceBean resourceBean = ctx.getBean(ResourceBean.class); ResourceLoader loader = resourceBean.getResourceLoader(); Assert.assertTrue(loader instanceof ApplicationContext); }
使用Resource作爲屬性
注入Resource
Spring提供了一個PropertyEditor “ResourceEditor”用於在注入的字符串和Resource之間進行轉換。因此可以使用注入方式注入Resource。
ResourceEditor完全使用ApplicationContext根據注入的路徑字符串獲取相應的Resource,說白了還是自己做還是容器幫你做的問題。準備Bean
package com.heqing.spring.bean; import org.springframework.core.io.Resource; public class ResourceBean3 { private Resource resource; public Resource getResource() { return resource; } public void setResource(Resource resource) { this.resource = resource; } }
準備配置文件(chapter/ resourceInject.xml):
<bean id="resourceBean1" class="com.heqing.spring.bean.ResourceBean3"> <property name="resource" value="com/heqing/spring/test.properties"/> </bean> <bean id="resourceBean2" class="com.heqing.spring4.bean.ResourceBean3"> <property name="resource" value="classpath:com/heqing/spring/test.properties"/> </bean>
測試
@Test public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("chapter/resourceInject.xml"); ResourceBean3 resourceBean1 = ctx.getBean("resourceBean1", ResourceBean3.class); ResourceBean3 resourceBean2 = ctx.getBean("resourceBean2", ResourceBean3.class); Assert.assertTrue(resourceBean1.getResource() instanceof ClassPathResource); Assert.assertTrue(resourceBean2.getResource() instanceof ClassPathResource); }
使用路徑通配符加載Resource
- ? : 匹配一個字符,如“config?.xml”將匹配“config1.xml”;
- * : 匹配零個或多個字符串,如“cn/*/config.xml”將匹配“cn/javass/config.xml”,但不匹配匹配“cn/config.xml”;而“cn/config-.xml”將匹配“cn/config-dao.xml”;
- * : 配路徑中的零個或多個目錄,如“cn//config.xml”將匹配“cn/config.xml”,也匹配“cn/javass/spring/config.xml”;而“cn/javass/config-.xml”將匹配“cn/javass/config-dao.xml”,即把“*”當做兩個“*”處理。
前綴
classpath : 用於加載類路徑(包括jar包)中的一個且僅一個資源;對於多個匹配的也只返回一個,所以如果需要多個匹配的請考慮“classpath*:”前綴;
@Test public void testClasspathPrefix() throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //只加載一個絕對匹配Resource,且通過ResourceLoader.getResource進行加載 Resource[] resources=resolver.getResources("classpath:META-INF/INDEX.LIST"); Assert.assertEquals(1, resources.length); //只加載一個匹配的Resource,且通過ResourceLoader.getResource進行加載 resources = resolver.getResources("classpath:META-INF/*.LIST"); Assert.assertTrue(resources.length == 1); }
classpath* : 用於加載類路徑(包括jar包)中的所有匹配的資源。帶通配符的classpath使用“ClassLoader”的“Enumeration getResources(String name)”方法來查找通配符之前的資源,然後通過模式匹配來獲取匹配的資源。如“classpath:META-INF/*.LIST”將首先加載通配符之前的目錄“META-INF”,然後再遍歷路徑進行子路徑匹配從而獲取匹配的資源。
@Test public void testClasspathAsteriskPrefix () throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //將加載多個絕對匹配的所有Resource //將首先通過ClassLoader.getResources("META-INF")加載非模式路徑部分 //然後進行遍歷模式匹配 Resource[] resources=resolver.getResources("classpath*:META-INF/INDEX.LIST"); Assert.assertTrue(resources.length > 1); //將加載多個模式匹配的Resource resources = resolver.getResources("classpath*:META-INF/*.LIST"); Assert.assertTrue(resources.length > 1); }
file : 加載一個或多個文件系統中的Resource。如“file:D:/*.txt”將返回D盤下的所有txt文件;
- 無前綴 : 通過ResourceLoader實現加載一個資源。
注入Resource
<bean id="resourceBean1" class="com.heqing.spring.bean.ResourceBean"> <property name="resources"> <array> <value>com.heqing/spring/test.properties</value> <value>log4j.xml</value> </array> </property> </bean> <bean id="resourceBean2" class="com.heqing.spring.bean.ResourceBean"> <property name="resources" value="classpath*:META-INF/INDEX.LIST"/> </bean> <bean id="resourceBean3" class="com.heqing.spring.bean.ResourceBean"> <property name="resources"> <array> <value>com.heqing/spring/test.properties</value> <value>classpath*:META-INF/INDEX.LIST</value> </array> </property> </bean>
AppliacationContext實現對各種Resource的支持
ClassPathXmlApplicationContext
public class ClassPathXmlApplicationContext { //1)通過ResourcePatternResolver實現根據configLocation獲取資源 public ClassPathXmlApplicationContext(String configLocation); public ClassPathXmlApplicationContext(String... configLocations); public ClassPathXmlApplicationContext(String[] configLocations, ……); //2)通過直接根據path直接返回ClasspathResource public ClassPathXmlApplicationContext(String path, Class clazz); public ClassPathXmlApplicationContext(String[] paths, Class clazz); public ClassPathXmlApplicationContext(String[] paths, Class clazz, ……); }
第一類構造器是根據提供的配置文件路徑使用“ResourcePatternResolver ”的“getResources()”接口通過匹配獲取資源;即如“classpath:config.xml”
第二類構造器則是根據提供的路徑和clazz來構造ClassResource資源。即採用“public ClassPathResource(String path, Class< ?> clazz)”構造器獲取資源。
FileSystemXmlApplicationContext
將加載相對於當前工作目錄的“configLocation”位置的資源,注意在linux系統上不管“configLocation”是否帶“/”,都作爲相對路徑;而在window系統上如“D:/resourceInject.xml”是絕對路徑。因此在除非很必要的情況下,不建議使用該ApplicationContext。
//linux系統,第一個將相對於當前vm路徑進行加載; //第二個則是絕對路徑方式加載 ctx.getResource ("chapter4/config.xml"); ctx.getResource ("/root/confg.xml"); //windows系統,第一個將相對於當前vm路徑進行加載; //第二個則是絕對路徑方式加載 ctx.getResource ("chapter4/config.xml"); ctx.getResource ("d:/chapter4/confg.xml");
此處還需要注意:在linux系統上,構造器使用的是相對路徑,而ctx.getResource()方法如果以“/”開頭則表示獲取絕對路徑資源,而不帶前導“/”將返回相對路徑資源
因此如果需要加載絕對路徑資源最好選擇前綴“file”方式,將全部根據絕對路徑加載。如在linux系統“ctx.getResource (“file:/root/confg.xml”);”