Spring自动加载指定路径规则的文件--PathMatchingResourcePatternResolver

使用场景:

  根据配置路径自动加载符合路径规则的xml文件、类文件等等;

  查找范围:当前工程,当前工程依赖的jar包;

示例:

public void testGetResources(){
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    try {
      Resource[] metaInfResources = resourcePatternResolver
          .getResources("classpath*:**/*DAO.class");
      for(Resource r : metaInfResources){
        System.out.println("URL:" + r.getURL());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

输出结果:

URL:file:/D:/workspace/upd/sogou-passport/sogou-passport/passport-main-service/target/classes/com/sogou/upd/passport/dao/account/AccountAuthDAO.class
URL:file:/D:/workspace/upd/sogou-passport/sogou-passport/passport-main-service/target/classes/com/sogou/upd/passport/dao/account/AccountConnectDAO.class
URL:file:/D:/workspace/upd/sogou-passport/sogou-passport/passport-main-service/target/classes/com/sogou/upd/passport/dao/account/AccountDAO.class
URL:file:/D:/workspace/upd/sogou-passport/sogou-passport/passport-main-service/target/classes/com/sogou/upd/passport/dao/app/AppConfigDAO.class

研究源码:

1.getResources(locationPattern)方法

  首先判断是否以classpath*:前缀,如果是则判断locationPattern是否包含有通配符(*或?)、如果包含通配符则调用findPathMatchingResources方法、没有包含通配符就不需要解析了调用findAllClassPathResources方法。

2.findPathMatchingResources方法

protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
        String rootDirPath = determineRootDir(locationPattern);
        String subPattern = locationPattern.substring(rootDirPath.length());
        Resource[] rootDirResources = getResources(rootDirPath);
        Set<Resource> result = new LinkedHashSet<Resource>(16);
        for (Resource rootDirResource : rootDirResources) {
            rootDirResource = resolveRootDirResource(rootDirResource);
            if (isJarResource(rootDirResource)) {
                result.addAll(doFindPathMatchingJarResources(rootDirResource, subPattern));
            }
            else if (rootDirResource.getURL().getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
                result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirResource, subPattern, getPathMatcher()));
            }
            else {
                result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
        }
        return result.toArray(new Resource[result.size()]);
    }

     把locationPattern拆分成两部分:rootDirPath 和subPattern,rootDirPath是根目录路径,subPattern是子目录路径匹配规则字符串。历遍根目录下的所有子目录、并得到所有的子目录在doFindPathMatchingFileResources(rootDirResource, subPattern)方法中,再根据子目录逐个逐个去匹配subPattern。

 

posted @ 2013-04-19 03:18  跳刀的兔子  阅读(16373)  评论(0编辑  收藏  举报