Spring 学习笔记

spring resource以及ant路径匹配规则 源码学习

2018-01-31  本文已影响35人  jwfy

spring中resource是一个接口,为资源的抽象提供了一套操作方式,可匹配类似于classpath:XXX,file://XXX等不同协议的资源访问。

image.png

如上图所示,spring已经提供了多种访问资源的实体类,还有DefaultResourceLoader类,使得与具体的context结合。在spring中根据设置的配置文件路径转换为对应的文件资源


// AbstractBeanDefinitionReader 文件
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);

// DefaultResourceLoader 文件
public Resource getResource(String location) {
    Assert.notNull(location, "Location must not be null");

    for (ProtocolResolver protocolResolver : this.protocolResolvers) {
        Resource resource = protocolResolver.resolve(location, this);
        if (resource != null) {
            return resource;
        }
    }

    if (location.startsWith("/")) {
       // ClassPathContextResource 
        return getResourceByPath(location);
    }
    else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
        return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
        // 如果是以classpath:开头,认为是classpath样式的资源,返回ClassPathResource
    }
    else {
        try {
            URL url = new URL(location);
            return new UrlResource(url);
            // 符合URL协议,返回UrlResource
        }
        catch (MalformedURLException ex) {
            return getResourceByPath(location);
            // 剩下的无法判断的全部返回ClassPathContextResource
        }
    }
}

// 然后在真正的使用resource的文件流时,XmlBeanDefinitionReader文件内
InputStream inputStream = encodedResource.getResource().getInputStream();
image.png

有多种具体的Resource类的获取输入流的实现方式。
FileSystemResource 类

    public InputStream getInputStream() throws IOException {
        return new FileInputStream(this.file);
        // this.file 是个File对象
    }

ClassPathContextResource和ClassPathResource的获取IO流的方法是同一个

现在基本上清楚了spring针对不同协议的文件路径是如何操作路径,以什么样子的方式获取IO流,不过还是有几个疑问需要深入了解下。

匹配多个资源文件

之前说的例子都是明确指定context.xml 的情况,可是现实中会配置多个配置文件,然后依次加载,例如*.xml会匹配当前目录下面所有的.xml文件。来到了PathMatchingResourcePatternResolver.class匹配出多个xml的情况

至于为什么会定位到PathMatchingResourcePatternResolver.class这个文件,可以看

AbstractApplicationContext 文件

public AbstractApplicationContext() {
    this.resourcePatternResolver = getResourcePatternResolver();
}

protected ResourcePatternResolver getResourcePatternResolver() {
    return new PathMatchingResourcePatternResolver(this);
}

// 也就意味着在context类初始化的时候,就直接设置了好了resourcePatternResolver对象为PathMatchingResourcePatternResolver

PathMatchingResourcePatternResolver 文件

public Resource[] getResources(String locationPattern) throws IOException {
    Assert.notNull(locationPattern, "Location pattern must not be null");
    if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
        // 通过classpath:开头的地址
        if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
            // 地址路径中包含了 【*】这个匹配的关键字,意味着要模糊匹配
            return findPathMatchingResources(locationPattern);
        }
        else {
            // 查找当前所有的classpath资源并返回
            return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
        }
    }
    else {
        // and on Tomcat only after the "*/" separator for its "war:" protocol.
        int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
                locationPattern.indexOf(":") + 1);
        if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
            // 除去前缀,包含【*】,进行模糊匹配
            return findPathMatchingResources(locationPattern);
        }
        else {
            // 这个是针对具体的xml文件的匹配规则,会进入到DefaultResourceLoader装载资源文件
            return new Resource[] {getResourceLoader().getResource(locationPattern)};
        }
    }
}


// 根据模糊地址找出所有匹配的资源文件
protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
    String rootDirPath = determineRootDir(locationPattern);
    // 根路径,此处为xml/
    String subPattern = locationPattern.substring(rootDirPath.length());
    // 子路径,此处为*.xml
    Resource[] rootDirResources = getResources(rootDirPath);
    // 调用本身,算出根路径的资源信息
    // 如果为xml/*.xml 则返回一个根路径资源信息xml/
    // 如果为xml/**/*.xml 则还是返回一组根路径资源信息xml/
    Set<Resource> result = new LinkedHashSet<Resource>(16);
    for (Resource rootDirResource : rootDirResources) {
        rootDirResource = resolveRootDirResource(rootDirResource);
        URL rootDirURL = rootDirResource.getURL();
        // 获取其URL信息
        if (equinoxResolveMethod != null) {
            if (rootDirURL.getProtocol().startsWith("bundle")) {
                rootDirURL = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirURL);
                rootDirResource = new UrlResource(rootDirURL);
            }
        }
        if (rootDirURL.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
        // jboss的文件协议
            result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirURL, subPattern, getPathMatcher()));
        }
        else if (ResourceUtils.isJarURL(rootDirURL) || 
        isJarResource(rootDirResource)) {
           // jar包
            result.addAll(doFindPathMatchingJarResources(rootDirResource, rootDirURL, subPattern));
        }
        else {
           // 默认扫描当前的所有资源,添加到result中
            result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
    }
    return result.toArray(new Resource[result.size()]);
}

// 通过路径去匹配到合适的资源,此处的rootDir包含了绝对路径
protected Set<File> retrieveMatchingFiles(File rootDir, String pattern) 
      throws IOException {
    if (!rootDir.exists()) {
       // 根路径都不存在,则返回空
        if (logger.isDebugEnabled()) {
            logger.debug("Skipping [" + rootDir.getAbsolutePath() + "] because it does not exist");
        }
        return Collections.emptySet();
    }
    if (!rootDir.isDirectory()) {
        // 不是文件夹,返回空
        if (logger.isWarnEnabled()) {
            logger.warn("Skipping [" + rootDir.getAbsolutePath() + "] because it does not denote a directory");
        }
        return Collections.emptySet();
    }
    if (!rootDir.canRead()) {
       // 文件不可读,也返回空
        if (logger.isWarnEnabled()) {
            logger.warn("Cannot search for matching files underneath directory [" + rootDir.getAbsolutePath() +
                    "] because the application is not allowed to read the directory");
        }
        return Collections.emptySet();
    }
    String fullPattern = StringUtils.replace(rootDir.getAbsolutePath(), File.separator, "/");
    // 得到当前系统下的文件绝对地址
    if (!pattern.startsWith("/")) {
        fullPattern += "/";
    }
    fullPattern = fullPattern + StringUtils.replace(pattern, File.separator, "/");
    // 得到完整的全路径 例如/user/...*.xml
    Set<File> result = new LinkedHashSet<File>(8);
    doRetrieveMatchingFiles(fullPattern, rootDir, result);
    // 得到当前rootDir下面的所有文件,然后配合fullPattern进行匹配,得到的结果在result中
    return result;
}

protected void doRetrieveMatchingFiles(String fullPattern, File dir, Set<File> result) throws IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Searching directory [" + dir.getAbsolutePath() +
                "] for files matching pattern [" + fullPattern + "]");
    }
    File[] dirContents = dir.listFiles();
    // 得到当前根路径的所有文件(包含了文件夹)
    if (dirContents == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("Could not retrieve contents of directory [" + dir.getAbsolutePath() + "]");
        }
        return;
    }
    Arrays.sort(dirContents);
    // 这个也需要注意到,这个顺序决定了扫描文件的先后顺序,也意味着bean加载的情况
    for (File content : dirContents) {
        String currPath = StringUtils.replace(content.getAbsolutePath(), File.separator, "/");
        if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) {
          // 如果是文件夹,类似于xml/**/*.xml 文件
          // 访问到了** 就会是文件夹
            if (!content.canRead()) {
                ...
            }
            else {
               // 循环迭代访问文件
                doRetrieveMatchingFiles(fullPattern, content, result);
            }
        }
        if (getPathMatcher().match(fullPattern, currPath)) {
            result.add(content);
            // 匹配完成,添加到结果集合中
        }
    }
}

这样整个的xml文件读取过程就全部完成,也清楚了实际中xml文件是什么样的形式被访问到的。
其实spring的路径风格是和Apache Ant的路径样式一样的,Ant的更多细节可以自行学习了解。

FileSystemXmlApplicationContext和ClassPathXmlApplicationContext的区别

这个看名字就很明显,就是加载文件不太一样,一个通过纯粹的文件协议去访问,另一个却可以兼容多种协议。仔细分析他们的差异,会发现主要的差异就在于FileSystemXmlApplicationContext重写的getResourceByPath方法

FileSystemXmlApplicationContext 文件

protected Resource getResourceByPath(String path) {
    if (path != null && path.startsWith("/")) {
        path = path.substring(1);
    }
    return new FileSystemResource(path);
}

上面代码学习,已经清楚了在默认的中是生成ClassPathContextResource资源,但是重写之后意味着被强制性的设置为了FileSystemResource,就会出现文件不存在的情况。

如下图,设置的path只有context.xml,就会被提示找不到文件,因为此时的文件路径是项目路径 + context.xml

image.png

如果改为使用simple-spring-demo/src/main/resources/context.xml,此时需要注意修改xml内的properties文件路径,否则也会提示文件找不到

image.png image.png

这样就符合设置了,运行正常,这也告诉我们一旦使用FileSystemXmlApplicationContext记得修改所有的路径配置,以防止出现文件找不到的错误。

上一篇 下一篇

猜你喜欢

热点阅读