Spring 资源(上)

在日常程序开发中,处理外部资源是很繁琐的事情,我们可能需要处理URL资源、File资源资源、ClassPath相关资源、服务器相关资源(JBoss AS 5.x上的VFS资源)等等很多资源。因此处理这些资源需要使用不同的接口,这就增加了我们系统的复杂性;而且处理这些资源步骤都是类似的(打开资源、读取资源、关闭资源),因此如果能抽象出一个统一的接口来对这些底层资源进行统一访问,是不是很方便,而且使我们系统更加简洁,都是对不同的底层资源使用同一个接口进行访问。
Spring 提供一个Resource接口来统一这些底层资源一致的访问,而且提供了一些便利的接口,从而能提供我们的生产力。


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”);”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值