在日常程序開發中,處理外部資源是很繁瑣的事情,我們可能需要處理URL資源、File資源、ClassPath相關資源、服務器相關資源等等很多資源。因此處理這些資源需要使用不同的接口,這就增加了我們系統的複雜性;而且處理這些資源步驟都是類似的(打開資源、讀取資源、關閉資源),因此如果能抽象出一個統一的接口來對這些底層資源進行統一訪問,是不是很方便,而且使我們系統更加簡潔,都是對不同的底層資源使用同一個接口進行訪問。
spring提供一個Resource接口來統一這些底層資源一致的訪問,而且提供了一些便利的接口,從而能提高開發效率。
Resource接口
Spring的Resource接口代表底層外部資源,提供了對底層外部資源的一致性訪問接口。
public interface InputStreamSource{ //每次調用都將返回一個新的資源對應的java.io.InputStream字節流,調用者在使用完畢後必須關閉該資源 InputStream getInputStream() throws IOException; }
public interface Resource extends InputStreamSource{ //返回當前Resouce代表的底層資源是否存在,true表示存在 boolean exists(); //返回當前Resouce代表的底層資源是否可讀,true表示可讀 boolean isReadable(); //返回當前Resouce代表的底層資源是否已經打開,如果返回true,則只能被讀取一次然後關閉以避免內存泄露;常見的Resource實現一般返回false; boolean isOpen(); //如果當前Resouce代表的底層資源能由java.util.URL代表,則返回該URL,否則拋出IOException URL getURL() throws IOException; //如果當前Resouce代表的底層資源能由java.util.URI代表,則返回該URI,否則拋出IOException URI getURI() throws IOException; //如果當前Resouce代表的底層資源能由java.io.File代表,則返回該File,否則拋出IOException File getFile() throws IOException; //返回當前Resouce代表的底層文件資源的長度,一般的值代表的文件資源的長度 long contentLength() throws IOException; //返回當前Resouce代表的底層文件資源的最後修改時間 long lastModified() throws IOException; //用於創建相對於當前Resource代表的底層資源的資源,比如當前Resource代表文件資源“D:/test/”則createRelative("test.txt")將返回代表文件資源“D:/test/test.txt”Resource資源。 Resource createRelative(String relativePath) throws IOException; //返回當前Resource代表的底層文件資源的文件路徑,比如File資源:file://d:/test.txt 將返回d:/test.txt,而URL資源http://www.javass.cn將返回“”,因爲只返回文件路徑 String getFilename(); //返回當前Resource代表的底層資源的描述符,通常就是資源的全路徑(實際文件名或實際URL地址) String getDescription(); }
Resource接口提供了足夠的抽象,足夠滿足我們日常使用。而且提供了很多內置Resource實現:ByteArrayResource、InputStreamResource 、FileSystemResource 、UrlResource 、ClassPathResource、ServletContextResource、VfsResource等。
內置Resource實現
ByteArrayResource
ByteArrayResource代表 btye[]數組資源,對於getInputStream操作將返回一個ByteArrayInputStream
import java.io.IOException; import java.io.InputStream; import org.junit.Test; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; public class ResourceTest { @Test public void testByteArrayResource(){ //1.定義資源 Resource resource = new ByteArrayResource("hello".getBytes()); //2.驗證資源 if(resource.exists()){ //3.訪問資源 dumpStream(resource); } } private void dumpStream(Resource resource){ InputStream is = null; try { //1.獲取資源文件 is = resource.getInputStream(); //2.讀取資源文件 byte[] descBytes = new byte[is.available()]; is.read(descBytes); System.out.println(new String(descBytes)); } catch (IOException e) { e.printStackTrace(); } finally{ try { //3.關閉資源 is.close(); } catch (IOException e) { e.printStackTrace(); } } } }
dumpStream方法很抽象定義了訪問流的三部曲:打開資源、讀取資源、關閉資源
testByteArrayResouce方法也定義了基本步驟:定義資源、驗證資源存在、訪問資源
ByteArrayResource可多次讀取數組資源,即isOpen永遠是falseInputStreamResource
InputStreamResource代表Java.io.InputStream字節流,對於個體InputStream操作將直接返回該字節流,因此只能讀取一次字節流,即isOpen永遠返回true
@Test public void testInputStreamResource(){ ByteArrayInputStream bis = new ByteArrayInputStream("hello2".getBytes()); Resource resource = new InputStreamResource(bis); if (resource.exists()) { dumpStream(resource); } Assert.assertEquals(true, resource.isOpen()); }
FileSystemResource
FileSystemResource代表java.io.File資源,對於getInputStream 操作將返回底層文件的字節流,isOpen將永遠返回false,從而表示可多次讀取底層文件的字節流
@Test public void testFileSystemResource(){ File file = new File("d:/test.txt"); Resource resource = new FileSystemResource(file); if (resource.exists()) { dumpStream(resource); } Assert.assertEquals(false, resource.isOpen()); }
ClassPathResource
ClassPathResource代表classpath路徑的資源,將使用ClassLoader進行加載資源。classpath資源存在於類路徑中的文件系統中或jar包裏,且isOpen永遠返回false,表示可多次讀取資源。
ClassPathResource加載資源替代了Class類和ClassLoader類的getResource(String name)和getResouceAsStream(String name) 兩個加載類路徑資源方法,提供一致的訪問方式.public ClassPathResource(String path) : 使用默認的ClassLoader加載“path”類路徑資源;
@Test public void testClasspathResourceByDefaultClassLoader() throws IOException{ Resource resource = new ClassPathResource("com/lizhenhua/test3/db.properties"); if (resource.exists()) { dumpStream(resource); } System.out.println("path:" + resource.getFile().getAbsolutePath()); Assert.assertEquals(false, resource.isOpen()); }
public ClassPathResource(String path, ClassLoader classLoader) : 使用指定的ClassLoader加載path類路徑資源。使用指定的ClassLoader進行加載資源,將加載指定的ClassLoader類路徑上相對於根路徑的資源。也就是可以通過這種方式訪問jar包中的資源文件
@Test public void testClasspathResourceByClassLoader() throws IOException{ ClassLoader classLoader = TypeComparator.class.getClassLoader(); Resource resource = new ClassPathResource("META-INF/INDEX.LIST",classLoader); if (resource.exists()) { dumpStream(resource); } System.out.println("path:" + resource.getDescription()); Assert.assertEquals(false, resource.isOpen()); }
public ClassPathResource(String path, Class< ?> clazz) : 使用指定的類加載path類路徑資源,將加載相對於當前類的路徑的資源。
@Test public void testClasspathResourceByClass() throws IOException{ Class clazz = this.getClass(); Resource resource = new ClassPathResource("com/lizhenhua/test3/db.properties",clazz); if (resource.exists()) { dumpStream(resource); } System.out.println("path:" + resource.getDescription()); Assert.assertEquals(false, resource.isOpen()); Resource resource2 = new ClassPathResource("db.properties",clazz); if (resource2.exists()) { dumpStream(resource2); System.out.println(1); } System.out.println("path:" + resource2.getDescription()); Assert.assertEquals(false, resource2.isOpen()); }
UrlResource
UrlResource代表URL資源,用於簡化URL資源訪問。isOpen永遠返回false,可以多次讀取資源
支持如下資源訪問
http:通過標準的http協議訪問web資源,如new UrlResource(“http://地址”);
ftp:通過ftp協議訪問資源,如new UrlResource(“ftp://地址”);
file:通過file協議訪問本地文件系統資源 如:new UrlResource(file:d:/test.txt)
@Test public void testUrlResource() throws IOException{ Resource resource = new UrlResource("http://www.hao123.com"); if (resource.exists()) { dumpStream(resource); } System.out.println("path:" + resource.getURL().getPath()); Assert.assertEquals(false, resource.isOpen()); }
ServletContextResource
代表web應用資源,用於簡化servlet容器的ServletContext接口的getResource操作和getResourceAsStream操作
VfsResource
fsResource代表Jboss 虛擬文件系統資源。
Jboss VFS框架是一個文件系統資源訪問的抽象層,它能一致的訪問物理文件系統、jar資源、zip資源、war資源等,VFS能把這些資源一致的映射到一個目錄上,訪問它們就像訪問物理文件資源一樣,而其實這些資源不存在與物理文件系統。
在示例之前需要準備一些jar包,在此我們使用JBoss VFS3版本,
將Jboss-logging.jar和jboss-vfs.jar兩個jar包拷貝到我們項目的lib目錄中
@Test public void testVfsResourceForRealFileSystem() throws IOException { //1.創建一個虛擬的文件目錄 VirtualFile home = VFS.getChild("/home"); //2.將虛擬目錄映射到物理的目錄 VFS.mount(home, new RealFileSystem(new File("d:"))); //3.通過虛擬目錄獲取文件資源 VirtualFile testFile = home.getChild("test.txt"); //4.通過一致的接口訪問 Resource resource = new VfsResource(testFile); if(resource.exists()) { dumpStream(resource); } System.out.println("path:" + resource.getFile().getAbsolutePath()); Assert.assertEquals(false, resource.isOpen()); } @Test public void testVfsResourceForJar() throws IOException { //1.首先獲取jar包路徑 File realFile = new File("lib/org.springframework.beans-3.0.5.RELEASE.jar"); //2.創建一個虛擬的文件目錄 VirtualFile home = VFS.getChild("/home2"); //3.將虛擬目錄映射到物理的目錄 VFS.mountZipExpanded(realFile, home, TempFileProvider.create("tmp", Executors.newScheduledThreadPool(1))); //4.通過虛擬目錄獲取文件資源 VirtualFile testFile = home.getChild("META-INF/spring.handlers"); Resource resource = new VfsResource(testFile); if(resource.exists()) { dumpStream(resource); } System.out.println("path:" + resource.getFile().getAbsolutePath()); Assert.assertEquals(false, resource.isOpen()); }
訪問Resource
ResourceLoader接口
ResourceLoader接口用於返回Resource對象;其實現可以看作是一個生產Resource的工廠類。
public interface ResourceLoader { //用於根據提供的location參數返回相應的Resource對象 Resource getResource(String location); //返回加載這些Resource的ClassLoader。 ClassLoader getClassLoader(); }
Spring提供了一個適用於所有環境的DefaultResourceLoader實現,可以返回ClassPathResource、UrlResource;還提供一個用於web環境的ServletContextResourceLoader,它繼承了DefaultResourceLoader的所有功能,又額外提供了獲取ServletContextResource的支持。
@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。
public interface ResourceLoaderAware { void setResourceLoader(ResourceLoader resourceLoader); }
1.先準備測試Bean,我們的測試Bean還簡單隻需實現ResourceLoaderAware接口,然後通過回調將ResourceLoader保存下來就可以了:
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; } }
2.配置Bean定義(chapter4/resourceLoaderAware.xml):
<bean class="cn.javass.spring.chapter4.bean.ResourceBean"/>
3.測試
@Test public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("chapter4/resourceLoaderAware.xml"); ResourceBean resourceBean = ctx.getBean(ResourceBean.class); ResourceLoader loader = resourceBean.getResourceLoader(); Assert.assertTrue(loader instanceof ApplicationContext); }
注入Resource
Spring提供了一個PropertyEditor “ResourceEditor” 用於在注入的字符串和Resource之間進行轉換。因此可以使用注入方式注入Resource
ResourceEditor 完全使用ApplicationContext根據注入的路徑字符串獲取相應的Resource。
1.準備Bean:
public class ResourceBean3 { private Resource resource; public Resource getResource() { return resource; } public void setResource(Resource resource) { this.resource = resource; } }
2.準備配置文件:
<bean id="resourceBean1" class="cn.javass.spring.chapter4.bean.ResourceBean3"> <property name="resource" value="cn/javass/spring/chapter4/test1.properties"/> </bean> <bean id="resourceBean2" class="cn.javass.spring.chapter4.bean.ResourceBean3"> <property name="resource" value="classpath:cn/javass/spring/chapter4/test1.properties"/> </bean>
3.測試:
@Test public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("chapter4/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
- ? : 匹配一個字符
- * : 匹配零個或多個字符串
- ** : 匹配路徑中的零個或多個目錄
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="cn.javass.spring.chapter4.bean.ResourceBean4"> <property name="resources"> <array> <value>cn/javass/spring/chapter4/test1.properties</value> <value>log4j.xml</value> </array> </property> </bean> <bean id="resourceBean2" class="cn.javass.spring.chapter4.bean.ResourceBean4"> <property name="resources" value="classpath*:META-INF/INDEX.LIST"/> </bean> <bean id="resourceBean3" class="cn.javass.spring.chapter4.bean.ResourceBean4"> <property name="resources"> <array> <value>cn/javass/spring/chapter4/test1.properties</value> <value>classpath*:META-INF/INDEX.LIST</value> </array> </property> </bean>
Spring通過ResourceArrayPropertyEditor來進行類型轉換的,而它又默認使用“PathMatchingResourcePatternResolver”來進行把路徑解析爲Resource對象。所有大家只要會使用“PathMatchingResourcePatternResolver”,其它一些實現都是委託給它的,比如AppliacationContext的“getResources”方法等。
AppliacationContext實現對各種Resource的支持
ClassPathXmlApplicationContext
默認將通過classpath進行加載返回
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。
public class FileSystemXmlApplicationContext{ public FileSystemXmlApplicationContext(String configLocation); public FileSystemXmlApplicationContext(String... configLocations,……); }
//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");
因此如果需要加載絕對路徑資源最好選擇前綴“file”方式,將全部根據絕對路徑加載。如在linux系統“ctx.getResource (“file:/root/confg.xml”);”