2.spring资源访问利器

资源抽象接口

基本概念

         弥补JDK不能很好的访问底层资源(类路径,web上下文中获取资源的操作类)。Spring设计了一个资源Resource接口。

         主要实现方法:

                   boolean exists();//资源是否存在

                   boolean    isOpen();//文件是否打开

                   URL getURL() thows IOException //如果底层资源可以表示为URL则返回URL对象

                   File getFile() thows IOException //如果底层资源对应一个文件则返回File对象

         Spring框架使用resource装载各种资源,包括配置文件,国际化文件。

Resource接口及其实现类可以脱离spring框架使用。

Resource具体实现类

        

ByteArrayResource: 二进制数组资源。

ClassPathResource: 类路径下的资源。

FileSystemResource: 文件系统资源。

InputStreamResource: 以输入流形式返回资源。

ServletContextResource:负责对于WEB应用根目录路径资源下的加载,支持流和URL方式访问还可以访问jar包中的资源。

UrlResource:封装Java.net.URL,可以访问任何通过URL访问的资源。

示例代码:

package com.spring.demo.resources;

import java.io.File;
import java.io.IOException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class Main {
	public static void main(String[] args) throws IOException {
		String path="E:/javaproject/svsmwork/springdemo/spring-simple1.xml";
		Resource resource=new FileSystemResource(path);
		System.out.println(resource.getFilename());
		Resource resource1=new ClassPathResource("spring-simple1.xml");
		resource1.getFilename();
		File file=resource1.getFile();
		//file.
	}
}

 

资源加载

为访问不同类型资源,必须使用相应的Resource实现类,相对麻烦。Spring提供了另外一种机制,使用前缀识别不同资源。

地址前缀

示例

对于资源类型

classpath:

classpath: springdemo/spring-simple1.xml

从类路径资源加载,等价classpath:/,可在标准文件系统中使用,也可在jar包和zip类包中使用

file:

file: /springdemo/spring-simple1.xml

使UrlResource从文件系统加载资源,可使用相对路径和绝对路径

http://

http://www.xxxxx.com

使UrlResource从web服务器加载

ftp://

ftp://www.xxx.com

使UrlResource从ftp服务器加载

无前缀

/ springdemo/spring-simple1.xml

根据ApplicationContext的具体实现类采用对应的Resource类型

Ant匹配符:

?:匹配文件名中的一个字符

*:匹配文件名中任意字符

**:匹配多层路径

特殊示例:

classpath*: springdemo/spring-simple*.xml

表示从类路下加载所有spring-simple开头的xml资源文件

 

Spring定义了一套资源加载接口,并提供实现类

 

示例代码:

package com.spring.demo.resources;

import java.io.IOException;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

public class ResourceLoad {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        ResourcePatternResolver res=new PathMatchingResourcePatternResolver();
        //加载com/spring/demo/aop包下(及子包)下的所有xml文件
        Resource    res1[]=res.getResources("classpath*:com/spring/demo/aop/**/*.xml");
        for(Resource temp:res1){
            System.out.println(temp.getFilename());
        }
    }

}

 

posted on 2017-02-20 10:43  十三公子  阅读(116)  评论(0)    收藏  举报

导航