Spring源码学习IOC(1):Resource的分析

我们知道,在spring中,配置文件是通过资源形式加载的,我们首先来分析一些在spring中资源类的结构,并且查看一下资源的类型;

资源类图如下:





  1. public interface InputStreamSource {
  2.         /**
  3.          *用于获得资源的输入流
  4.          */
  5.     InputStream getInputStream() throws IOException;
  6. }
抽象出这层接口,事实上是把java底层的二进制流和spring中的resource给对应以来,把inputstream包装进Resource;



  1. public interface Resource extends InputStreamSource {
  2.     
  3.     boolean exists();
  4.     boolean isOpen();
  5.     
  6.     URL getURL() throws IOException;
  7.     File getFile() throws IOException;
  8.     Resource createRelative(String relativePath) throws IOException;
  9.     String getDescription();
  10.  


进一步抽象出Resource的功能接口,在这里,我们可以看出,在代码编写过程中,接口的设计是根据逻辑一步一步抽象出来的,不用吝啬接口的生成,按照接口隔离原则;
                                                                                                                       

  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.URL;

  6. /**
  7.  * Convenience base class for {@link Resource} implementations,
  8.  * pre-implementing typical behavior.
  9.  *
  10.  * <p>The "exists" method will check whether a File or InputStream can
  11.  * be opened; "isOpen" will always return false; "getURL" and "getFile"
  12.  * throw an exception; and "toString" will return the description.
  13.  *
  14.  * @author Juergen Hoeller
  15.  * @since 28.12.2003
  16.  */
  17. public abstract class AbstractResource implements Resource {
  1.     public boolean exists() {
  2.         // Try file existence: can we find the file in the file system?
  3.         try {
  4.             return getFile().exists();
  5.         }
  6.         catch (IOException ex) {
  7.             // Fall back to stream existence: can we open the stream?
  8.             try {
  9.                 InputStream is = getInputStream();
  10.                 is.close();
  11.                 return true;
  12.             }
  13.             catch (Throwable isEx) {
  14.                 return false;
  15.             }
  16.         }
  17.     }
  18.     public boolean isOpen() {
  19.         return false;
  20.     }
  21.     
  22.     public URL getURL() throws IOException {
  23.         throw new FileNotFoundException(getDescription() + " cannot be resolved to URL");
  24.     }
  25.     
  26.     public File getFile() throws IOException {
  27.         throw new FileNotFoundException(getDescription() + " cannot be resolved to absolute file path");
  28.     }
  29.     
  30.     public Resource createRelative(String relativePath) throws IOException {
  31.         throw new FileNotFoundException("Cannot create a relative resource for " + getDescription());
  32.     }
  33.     
  34.     public String getFilename() throws IllegalStateException {
  35.         throw new IllegalStateException(getDescription() + " does not carry a filename");
  36.     }
  37.     public abstract String getDescription();
  38.     public String toString() {
  39.         return getDescription();
  40.     }
  41.     public boolean equals(Object obj) {
  42.         return (obj == this ||
  43.             (obj instanceof Resource && ((Resource) obj).getDescription().equals(getDescription())));
  44.     }
  45.     
  46.     public int hashCode() {
  47.         return getDescription().hashCode();
  48.     }

抽象出来的Resource功能接口对于下面多种不同类型的资源,其有很多功能接口的实现势必是相同的,所以在这里spring建立了一个抽象类,在设计模式中,抽象类应该做到的是,尽量把子类相同的功能方法放到抽象父类中实现,增加复用,而尽量把少的数据推到子类中实现,减少空间的消耗;

                 

在这类Resource中,我们使用得最多的,估计就是要属于ClassPathResource和FileSystemReource;顾名思意,这两种资源类分别是默认在ClassPath和FileSystem下查找资源;而我们用得最多的是classPath,因为这样对工程的移植更有利;


public class FileSystemResource extends AbstractResource {

    private final File file;

    private final String path;

    public FileSystemResource(File file) {
        Assert.notNull(file, "File must not be null");
        this.file = file;
        this.path = StringUtils.cleanPath(file.getPath());
    }

   
    public FileSystemResource(String path) {
        Assert.notNull(path, "Path must not be null");
        this.file = new File(path);
        this.path = StringUtils.cleanPath(path);
    }

    
    public final String getPath() {
        return this.path;
    }


    public boolean exists() {
        return this.file.exists();
    }

    
    public InputStream getInputStream() throws IOException {
        return new FileInputStream(this.file);
    }

    public URL getURL() throws IOException {
        return new URL(ResourceUtils.FILE_URL_PREFIX + this.file.getAbsolutePath());
    }

   
    public File getFile() {
        return file;
    }

    
    public Resource createRelative(String relativePath) {
        String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
        return new FileSystemResource(pathToUse);
    }

    
    public String getFilename() {
        return this.file.getName();
    }

  
    public String getDescription() {
        return "file [" + this.file.getAbsolutePath() + "]";
    }

    public boolean equals(Object obj) {
        return (obj == this ||
            (obj instanceof FileSystemResource && this.path.equals(((FileSystemResource) obj).path)));
    }

    public int hashCode() {
        return this.path.hashCode();
    }

}


在VStringUtil中,我们可以看见如下代码:

public static String replace(String inString, String oldPattern, String newPattern) {
        if (inString == null) {
            return null;
        }
        if (oldPattern == null || newPattern == null) {
            return inString;
        }

        StringBuffer sbuf = new StringBuffer();
        // output StringBuffer we'll build up
        int pos = 0; // our position in the old string
        int index = inString.indexOf(oldPattern);
        // the index of an occurrence we've found, or -1
        int patLen = oldPattern.length();
        while (index >= 0) {
            sbuf.append(inString.substring(pos, index));
            sbuf.append(newPattern);
            pos = index + patLen;
            index = inString.indexOf(oldPattern, pos);
        }
        sbuf.append(inString.substring(pos));

        // remember to append any characters to the right of a match
        return sbuf.toString();
    }

是将//tihuan成/的代码,我们可见,在这段代码中,对传入的参数进行了严密的验证,正如代码大全中所介绍的防御性编程,我们假定从public传入进来的参数都是不安全的,只有在私有方法中,我们才对传入的参数不进行合法验证;

在这里,我们很明显的看出,代码中使用了适配器模式中的类适配器,在新的接口中,我们用resource接口包装了File,
在新的接口中,我们依然能访问file的isExist方法,却丝毫不知道我们是用的file;
其中,StrigUtils类是一个工具,他对path进行了预处理,处理了如//分解符和.  ..等文件路径描述的特殊操作符
另外的byte等资源,跟bye和ByteInputeStream的关系是类似的,分别是把不同源的数据当作资源,不过ClasspathResource不同的是,你可以传入ClassLoader或者Class来制定当前的类加载器,从而可以确定资源文件的BascDir
如果你不制定classLoader的话和Class的话,那么就会默认是当前线程的ClassLoader,而在这里,PATH和ClassLoader的预处理,都是经过了一个工具类来进行的,可以,在总段代码中,我们看见了很多的复用性和组织性,很多细节的方面的值得我们效仿和学习;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值