导航

Spring资源文件的加载

Posted on 2013-03-28 16:24  曙光城邦  阅读(723)  评论(0编辑  收藏  举报

Spring中的Resource接口(org.springframework.core.io包下),代表了任意位置的资源。包括文件系统中,classpath中,或者一个网络url中的资源。

可以通过Spring的ResourceLoader类,装载文件系统、classpath、Url中的资源文件。

如平时工程需要加载文件系统中的配置文件,或者类路径下,或者网络中的都可以使用它轻松的实现。

 

方式一:

通过资源装载器ResourceLoader类,加载资源

public class ResourceLoaderTest  implements ResourceLoaderAware{
    /**
     * 通过资源装载器加载一个资源
     */
    private ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader=resourceLoader;
    }
    
    public void printTxtContent() throws Exception{
        Resource resource = resourceLoader.getResource("http://www.cnblogs.com/robots.txt");//装载一个网络资源,cnblogs的robots.txt文件
        
        if(resource.exists()){
            BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
             while(true){
                 String line = br.readLine();
                 if(line==null)break;
                 System.out.println(line);
             }
             br.close();
        }
    }
    
}

实现ResourceLoaderAware接口的类,会在容器实例化类后给织入ResourceLoader实例。通过ResourceLoader的getResource方法即可获得资源。

getResource方法需要传入资源的位置:

1、文件系统使用 file:    如 file:c/hi.txt      路径使用linux下的正斜杆/

2、类路径下使用classpath:  如 classpath:com/zk/config.txt       就是com.zk包下的config.txt

3、网络资源Url      直接使用http://开头的网址    如:http://www.cnblogs.com/robots.txt

 

方式二、 直接在applicationContext配置文件中,指定资源位置。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.springframework.core.io.Resource;

public class ResourceLoaderConfig {

    /**
     * 通过配置文件注入资源
     */
    private Resource resource;
    
    public void setResource(Resource resource){
        this.resource=resource;
    }
    
    /**打印资源
     * @throws Exception
     */
    public void printResource() throws Exception{
        if(resource.exists()){
            BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
             while(true){
                 String line = br.readLine();
                 if(line==null)break;
                 System.out.println(line);
             }
             br.close();
        }
    }
}

配置文件

 <bean id="resourceLoaderConfig" class="com.zk.ResourceLoaderConfig">
 <property name="resource">
     <value>file:d:/hello.txt</value> 
 </property>
  </bean>


注意这里是通过配置文件注入resource属性的,而它的值就是资源的路径字符串。

此时在类中申明的变量是Resource,而不是ResourceLoader。

 

总结:

   使用方法二适配性更高更方便,但方法一是方法二的原理吧。

总之Resource接口抽象了所有位置的资源,而file,classpath,Url这些资源路径指定了资源的位置。最终使用资源装载器装载了该位置的资源。