Spring Resource 加载文件的方式

在使用spring作为容器进行项目开发中会有很多的配置文件,这些配置文件都是通过Spring的Resource接口来实现加载,其实Spring的Resource接口是对java.net.URL的一个强化,因为我们的配置文件不仅仅是来自于http请求或者ftp请求,还有很多classpath或者fileSystem或者InputStream(很少见),为了解决这个需求Spring开发了Resource接口:

Resource接口源码如下:

package org.springframework.core.io;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;

public interface Resource extends InputStreamSource {

    boolean exists();

    boolean isReadable();

    boolean isOpen();

    URL getURL() throws IOException;

    URI getURI() throws IOException;

    File getFile() throws IOException;

    long contentLength() throws IOException;

    long lastModified() throws IOException;

    Resource createRelative(String relativePath) throws IOException;

    String getFilename();

    String getDescription();

}

Resource只是一个标准,一个用于解决上面说到的需求的标准,具体的使用方式有以下几种:

1.引用http资源:

2.引用classpath资源:

3.引用fileSystem资源:

4.使用相对路径的资源:

code如下:

        ClassPathXmlApplicationContext cx = new ClassPathXmlApplicationContext();
        //http:
        Resource template1 = cx.getResource("http://www.chexiang.com");
        //classpath:
        Resource template2 = cx.getResource("calsspath:xxx.text");
        //fileSystem:
        Resource template3 = cx.getResource("file:xsd/spring-aop-3.1.xsd");
        //相对路径:必须和当前的ApplicationContext路径在一起
        Resource template4 = cx.getResource("/test/Messenger.groovy");

posted on 2014-04-22 23:34  把-大象装进-冰箱  阅读(1530)  评论(0编辑  收藏  举报