Java 类org.springframework.core.type.classreading.CachingMetadataReaderFactory 实例源码

项目:xproject    文件:ClassScanningUtils.java   
/**
 * <p>根据多个包名搜索class
 * 例如: ScanClassUtils.scanPakcages("javacommon.**.*");</p>
 * 
 * @param basePackages 各个包名使用逗号分隔,各个包名可以有通配符
 * @return 类名的集合
 */
@SuppressWarnings("all")
public static List<String> scanPackages(String basePackages) {
    Assert.notNull(basePackages,"'basePakcages' must be not null");
    ResourcePatternResolver rl = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(rl); 
    List<String> result = new ArrayList<String>();
    String[] arrayPackages = basePackages.split(",");
    try {
        for(int j = 0; j < arrayPackages.length; j++) {
            String packageToScan = arrayPackages[j];
            String packagePart = packageToScan.replace('.', '/');
            String classPattern = "classpath*:/" + packagePart + "/**/*.class";
            Resource[] resources = rl.getResources(classPattern);
            for (int i = 0; i < resources.length; i++) {
                Resource resource = resources[i];
                MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);   
                String className = metadataReader.getClassMetadata().getClassName();
                result.add(className);
            }
        }
    } catch(Exception e) {
        throw new RuntimeException(String.format("Scanning package[%s] class occurred an error!", basePackages), e);
    }
    return result;
}
项目:spring-batch-support    文件:AutomaticJobRegistrarConfigurationSupport.java   
protected List<Class<?>> findMyTypes(String basePackage) throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class<?>> candidates = new ArrayList<>();
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage(basePackage)
                               + "/" + "**/*.class";
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (isCandidate(metadataReader)) {
                candidates.add(forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }
    return candidates;
}
项目:mango-spring-boot-starter    文件:MangoDaoAutoCreator.java   
private List<Class<?>> findMangoDaoClasses(String packages) {
    try {
        List<Class<?>> daos = new ArrayList<Class<?>>();
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
        for (String locationPattern : getLocationPattern(packages)) {
            Resource[] rs = resourcePatternResolver.getResources(locationPattern);
            for (Resource r : rs) {
                MetadataReader reader = metadataReaderFactory.getMetadataReader(r);
                AnnotationMetadata annotationMD = reader.getAnnotationMetadata();
                if (annotationMD.hasAnnotation(DB.class.getName())) {
                    ClassMetadata clazzMD = reader.getClassMetadata();
                    daos.add(Class.forName(clazzMD.getClassName()));
                }
            }
        }
        return daos;
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
项目:jwx    文件:ClasspathPackageScanner.java   
/**
 * 将符合条件的Bean以Class集合的形式返回
 * 
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
public Set<Class<?>> getClassSet() throws IOException, ClassNotFoundException {
    this.classSet.clear();
    if (!this.packagesList.isEmpty()) {
        for (String pkg : this.packagesList) {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                    + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
            Resource[] resources = this.resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader reader = readerFactory.getMetadataReader(resource);
                    String className = reader.getClassMetadata().getClassName();
                    if (matchesEntityTypeFilter(reader, readerFactory)) {
                        this.classSet.add(Class.forName(className));
                    }
                }
            }
        }
    }
    return this.classSet;
}
项目:hibatis    文件:ClassScanner.java   
/**
 * 将符合条件的Bean以Class集合的形式返回
 * @throws Exception 异常
 * @return 类集合
 */
public Set<Class<?>> scan() throws Exception {
    Set<Class<?>> classSet = new HashSet<Class<?>>();
    if (!this.packagesList.isEmpty()) {
        for (String pkg : this.packagesList) {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
            Resource[] resources = this.resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader reader = readerFactory.getMetadataReader(resource);
                    String className = reader.getClassMetadata().getClassName();
                    if (matchesEntityTypeFilter(reader, readerFactory)) {
                        classSet.add(Class.forName(className));
                    }
                }
            }
        }
    }
    return classSet;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SpringPackageScanClassResolver.java   
@Override
protected void findAllClasses(String packageName, ClassLoader loader) {
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(
            loader);
    try {
        Resource[] resources = scan(loader, packageName);
        for (Resource resource : resources) {
            Class<?> clazz = loadClass(loader, metadataReaderFactory, resource);
            if (clazz != null) {
                addFoundClass(clazz);
            }
        }
    }
    catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
项目:spring-boot-concourse    文件:SpringPackageScanClassResolver.java   
@Override
protected void findAllClasses(String packageName, ClassLoader loader) {
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(
            loader);
    try {
        Resource[] resources = scan(loader, packageName);
        for (Resource resource : resources) {
            Class<?> clazz = loadClass(loader, metadataReaderFactory, resource);
            if (clazz != null) {
                addFoundClass(clazz);
            }
        }
    }
    catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
项目:MultimediaDesktop    文件:HandlerAnnotationFactoryBean.java   
private void beforeHandlerResource(
        ConcurrentHashMap<String, ConcurrentHashMap<HandlerScope, LinkedList<String>>> handlersMap) {
    try {

        if (!this.packagesList.isEmpty()) {
            for (String pkg : this.packagesList) {
                String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                        + ClassUtils.convertClassNameToResourcePath(pkg)
                        + RESOURCE_PATTERN;
                Resource[] resources = this.resourcePatternResolver
                        .getResources(pattern);
                MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(
                        this.resourcePatternResolver);

                onHandlerResource(resources, readerFactory, handlersMap);

            }
        }
    } catch (IOException e) {
        log.fatal("扫描业务处理异常", e);
    }
}
项目:kc-rice    文件:CustomTagAnnotations.java   
/**
 * Finds all the classes which have a BeanTag or BeanTags annotation
 *
 * @param basePackage the package to start in
 * @return classes which have BeanTag or BeanTags annotation
 * @throws IOException
 * @throws ClassNotFoundException
 */
protected static List<Class<?>> findTagClasses(String basePackage) throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class<?>> classes = new ArrayList<Class<?>>();

    String resolvedBasePackage = ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(
            basePackage));
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            resolvedBasePackage + "/" + "**/*.class";

    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (metadataReader != null && isBeanTag(metadataReader)) {
                classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }

    return classes;
}
项目:contestparser    文件:SpringPackageScanClassResolver.java   
@Override
protected void findAllClasses(String packageName, ClassLoader loader) {
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(
            loader);
    try {
        Resource[] resources = scan(loader, packageName);
        for (Resource resource : resources) {
            Class<?> clazz = loadClass(loader, metadataReaderFactory, resource);
            if (clazz != null) {
                addFoundClass(clazz);
            }
        }
    }
    catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
项目:openmrs-module-legacyui    文件:DeprecationCheckTest.java   
/**
 * Returns a list of class names which contain the {@literal @}Deprecated annotation. Does this search ONLY for
 * DWR*Service classes.
 *
 * Found the basic code here:
 * http://stackoverflow.com/questions/1456930/how-do-i-read-all-classes-from-a-java-package-in-the-classpath
 *
 * @return List of classes which contain the Deprecated annotation ({@literal @}Deprecated)
 * @throws IOException
 * @throws ClassNotFoundException
 */
private List<String> findDWRServiceClassesWhichContainDeprecatedAnnotation() throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    //Search only for Service Classes in DWR package.
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
            + resolveBasePackage(OPENMRS_DWR_PACKAGE_NAME) + "/**/*Service.class";

    List<String> candidateClasses = new ArrayList<String>();
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (doesClassContainDeprecatedAnnotation(metadataReader)) {
                candidateClasses.add(metadataReader.getClassMetadata().getClassName());
            }
        }
    }

    return candidateClasses;
}
项目:kaif    文件:ClassScanner.java   
public static List<Class> searchAnnotatedClasses(String basePackage, Class<?> annotation)
    throws IOException, ClassNotFoundException {
  ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
  MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(
      resourcePatternResolver);

  List<Class> candidates = new ArrayList<>();
  String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
      resolveBasePackage(basePackage) + "/" + "**/*.class";
  Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
  for (Resource resource : resources) {
    if (resource.isReadable()) {
      MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
      if (isCandidate(metadataReader, annotation)) {
        candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
      }
    }
  }
  return candidates;
}
项目:modules    文件:CSDReferenceFinder.java   
private Set<Class> findAnnotatedClasses(String packageName, Class annotationClass) throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            ClassUtils.convertClassNameToResourcePath(packageName) + "/**/*.class";
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);

    Set<Class> classes = new HashSet<>();
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            Class c = Class.forName(metadataReader.getClassMetadata().getClassName());
            if (c != null && c.getAnnotation(annotationClass) != null) {
                classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }
    return classes;
}
项目:rice    文件:CustomTagAnnotations.java   
/**
 * Finds all the classes which have a BeanTag or BeanTags annotation
 *
 * @param basePackage the package to start in
 * @return classes which have BeanTag or BeanTags annotation
 * @throws IOException
 * @throws ClassNotFoundException
 */
protected static List<Class<?>> findTagClasses(String basePackage) throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class<?>> classes = new ArrayList<Class<?>>();

    String resolvedBasePackage = ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(
            basePackage));
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            resolvedBasePackage + "/" + "**/*.class";

    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (metadataReader != null && isBeanTag(metadataReader)) {
                classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }

    return classes;
}
项目:spring-boot-starter-batch-web    文件:AutomaticJobRegistrarConfiguration.java   
private List<Class<?>> findMyTypes(String basePackage) throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class<?>> candidates = new ArrayList<Class<?>>();
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage(basePackage)
    + "/" + "**/*.class";
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (isCandidate(metadataReader)) {
                candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }
    return candidates;
}
项目:gizmo-v3    文件:SpringApplicationContextTest.java   
private List<Class> listClasses(String basePackage) throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class> candidates = new ArrayList<>();
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            resolveBasePackage(basePackage) + "/" + "**/*.class";
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
        }
    }
    return candidates;
}
项目:HotswapAgent    文件:ClassPathBeanDefinitionScannerAgent.java   
private void resetCachingMetadataReaderFactoryCache() {
    if (getMetadataReaderFactory() instanceof CachingMetadataReaderFactory) {
        Map metadataReaderCache = (Map) ReflectionHelper.getNoException(getMetadataReaderFactory(),
                CachingMetadataReaderFactory.class, "metadataReaderCache");

        if (metadataReaderCache == null)
            metadataReaderCache = (Map) ReflectionHelper.getNoException(getMetadataReaderFactory(),
                    CachingMetadataReaderFactory.class, "classReaderCache");

        if (metadataReaderCache != null) {
            metadataReaderCache.clear();
            LOGGER.debug("Cache cleared: CachingMetadataReaderFactory.clearCache()");
        } else {
            LOGGER.warning("Cache NOT cleared: neither CachingMetadataReaderFactory.metadataReaderCache nor clearCache does not exist.");
        }


    }
}
项目:kuali_rice    文件:CustomTagAnnotations.java   
/**
 * Finds all the classes which have a BeanTag or BeanTags annotation
 *
 * @param basePackage the package to start in
 * @return classes which have BeanTag or BeanTags annotation
 * @throws IOException
 * @throws ClassNotFoundException
 */
private static List<Class<?>> findTagClasses(String basePackage) throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class<?>> classes = new ArrayList<Class<?>>();
    String resolvedBasePackage = ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(
            basePackage));
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            resolvedBasePackage + "/" + "**/*.class";
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (metadataReader != null && isBeanTag(metadataReader)) {
                classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }
    return classes;
}
项目:aw-reporting    文件:CsvReportEntitiesMapping.java   
/**
 * Finds the beans classes that are annotated with {@code CsvReport} and extends the
 * {@code Report} base class.
 *
 * @param basePackage the package to be scanned.
 * @return the list of classes that match the requirements to be a report bean.
 */
private List<Class<? extends Report>> findReportBeans(String basePackage) throws IOException,
    ClassNotFoundException {
  ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
  MetadataReaderFactory metadataReaderFactory =
      new CachingMetadataReaderFactory(resourcePatternResolver);
  String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
      + resolveBasePackage(basePackage) + "/" + "**/*.class";
  Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);

  List<Class<? extends Report>> candidates = new ArrayList<Class<? extends Report>>();
  for (Resource resource : resources) {
    addCandidateIfApplicable(resource, metadataReaderFactory, candidates);
  }

  return candidates;
}
项目:mybatis-plus-mini    文件:PackageHelper.java   
/**
   * <p>
   * 别名通配符设置
   * </p>
   * <p>
   * <property name="typeAliasesPackage" value="com.baomidou.*.entity"/>
   * </p>
   *
   * @param typeAliasesPackage 类别名包路径
   * @return
   */
  public static String[] convertTypeAliasesPackage(String typeAliasesPackage) {
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
      String pkg = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
              + ClassUtils.convertClassNameToResourcePath(typeAliasesPackage) + "/*.class";

/*
       * 将加载多个绝对匹配的所有Resource
 * 将首先通过ClassLoader.getResource("META-INF")加载非模式路径部分,然后进行遍历模式匹配,排除重复包路径
 */
      try {
          Set<String> set = new HashSet<>();
          Resource[] resources = resolver.getResources(pkg);
          if (resources != null && resources.length > 0) {
              MetadataReader metadataReader;
              for (Resource resource : resources) {
                  if (resource.isReadable()) {
                      metadataReader = metadataReaderFactory.getMetadataReader(resource);
                      set.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
                  }
              }
          }
          if (!set.isEmpty()) {
              return set.toArray(new String[]{});
          } else {
              throw new MybatisPlusException("not find typeAliasesPackage:" + pkg);
          }
      } catch (Exception e) {
          throw new MybatisPlusException("not find typeAliasesPackage:" + pkg, e);
      }
  }
项目:rocketmq-easyclient    文件:ScanPackage.java   
/**
 * 根据扫描包的,查询下面的所有类
 *
 * @param scanPackages 扫描的package路径
 * @return
 */
public static Set<String> findPackageClass(String scanPackages)
{
    if (StringUtils.isEmpty(scanPackages))
    {
        return Collections.EMPTY_SET;
    }
    //验证及排重包路径,避免父子路径多次扫描
    Set<String> packages = checkPackage(scanPackages);
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
    Set<String> clazzSet = new HashSet<String>();
    for (String basePackage : packages)
    {
        if (StringUtils.isEmpty(basePackage))
        {
            continue;
        }
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + org.springframework.util.ClassUtils.convertClassNameToResourcePath(
                        SystemPropertyUtils.resolvePlaceholders(basePackage))
                + "/" + DEFAULT_RESOURCE_PATTERN;
        try
        {
            Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
            for (Resource resource : resources)
            {
                //检查resource,这里的resource都是class
                String clazz = loadClassName(metadataReaderFactory, resource);
                clazzSet.add(clazz);
            }
        }
        catch (Exception e)
        {
            LOG.error("获取包下面的类信息失败,package:" + basePackage, e);
        }

    }
    return clazzSet;
}
项目:lams    文件:ConfigurationClassPostProcessor.java   
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
    this.beanClassLoader = beanClassLoader;
    if (!this.setMetadataReaderFactoryCalled) {
        this.metadataReaderFactory = new CachingMetadataReaderFactory(beanClassLoader);
    }
}
项目:sharding-quickstart    文件:PackageUtil.java   
/**
 * 根据扫描包的,查询下面的所有类
 *
 * @param scanPackages
 *            扫描的package路径
 * @return
 */
public static Set<String> findPackageClass(String scanPackages) {
    if (StringUtils.isBlank(scanPackages)) {
        return Collections.emptySet();
    }
    // 验证及排重包路径,避免父子路径多次扫描
    Set<String> packages = checkPackage(scanPackages);
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory =
            new CachingMetadataReaderFactory(resourcePatternResolver);
    Set<String> clazzSet = new HashSet<String>();
    for (String basePackage : packages) {
        if (StringUtils.isBlank(basePackage)) {
            continue;
        }
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + org.springframework.util.ClassUtils
                    .convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage))
                + "/" + DEFAULT_RESOURCE_PATTERN;
        try {
            Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
            for (Resource resource : resources) {
                // 检查resource,这里的resource都是class
                String clazz = loadClassName(metadataReaderFactory, resource);
                clazzSet.add(clazz);
            }
        }
        catch (Exception e) {
            log.error("获取包内shard方法失败,package:" + basePackage, e);
        }
    }
    return clazzSet;
}
项目:spring4-understanding    文件:ConfigurationClassPostProcessor.java   
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
    this.beanClassLoader = beanClassLoader;
    if (!this.setMetadataReaderFactoryCalled) {
        this.metadataReaderFactory = new CachingMetadataReaderFactory(beanClassLoader);
    }
}
项目:spring4-understanding    文件:AsmCircularImportDetectionTests.java   
@Override
protected ConfigurationClassParser newParser() {
    return new ConfigurationClassParser(
            new CachingMetadataReaderFactory(),
            new FailFastProblemReporter(),
            new StandardEnvironment(),
            new DefaultResourceLoader(),
            new AnnotationBeanNameGenerator(),
            new DefaultListableBeanFactory());
}
项目:osframe    文件:LoadPackageClasses.java   
/**
 * 将符合条件的Bean以Class集合的形式返回
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
public Set<Class<?>> getClassSet() throws IOException, ClassNotFoundException {
    this.classSet.clear();
    if (!this.packagesList.isEmpty()) {
        for (String pkg : this.packagesList) {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
            Resource[] resources = this.resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader reader = readerFactory.getMetadataReader(resource);
                    String className = reader.getClassMetadata().getClassName();
                    if (matchesEntityTypeFilter(reader, readerFactory)) {
                        this.classSet.add(Class.forName(className));
                    }
                }
            }
        }
    }
    //输出日志
    if (logger.isInfoEnabled()){
        for (Class<?> clazz : this.classSet) {
            logger.info(String.format("Found class:%s", clazz.getName()));
        }
    }
    return this.classSet;
}
项目:my-spring-cache-redis    文件:ConfigurationClassPostProcessor.java   
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
    this.beanClassLoader = beanClassLoader;
    if (!this.setMetadataReaderFactoryCalled) {
        this.metadataReaderFactory = new CachingMetadataReaderFactory(beanClassLoader);
    }
}
项目:sharding-mybatis    文件:ShardScanner.java   
/**
 * 将符合条件的Bean以Class集合的形式返回
 * 
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
public Set<Class<?>> getClassSet() throws IOException, ClassNotFoundException {
    this.classSet.clear();
    if (!this.packagesList.isEmpty()) {
        for (String pkg : this.packagesList) {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                    + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
            Resource[] resources = this.resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader reader = readerFactory.getMetadataReader(resource);
                    String className = reader.getClassMetadata().getClassName();
                    if (matchesEntityTypeFilter(reader, readerFactory)) {
                        this.classSet.add(Class.forName(className));
                    }
                }
            }
        }
    }
    // 输出日志
    if (logger.isInfoEnabled()) {
        for (Class<?> clazz : this.classSet) {
            logger.info(String.format("Found class:%s", clazz.getName()));
        }
    }
    return this.classSet;
}
项目:mybatis-plus    文件:PackageHelper.java   
/**
  * <p>
  * 别名通配符设置
  * </p>
  * <p>
  * <property name="typeAliasesPackage" value="com.baomidou.*.entity"/>
  * </p>
  *
  * @param typeAliasesPackage 类别名包路径
  * @return
  */
 public static String[] convertTypeAliasesPackage(String typeAliasesPackage) {
     ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
     MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
     String pkg = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
             + ClassUtils.convertClassNameToResourcePath(typeAliasesPackage) + "/*.class";
     /*
      * 将加载多个绝对匹配的所有Resource
* 将首先通过ClassLoader.getResource("META-INF")加载非模式路径部分,然后进行遍历模式匹配,排除重复包路径
*/
     try {
         Set<String> set = new HashSet<>();
         Resource[] resources = resolver.getResources(pkg);
         if (resources != null && resources.length > 0) {
             MetadataReader metadataReader;
             for (Resource resource : resources) {
                 if (resource.isReadable()) {
                     metadataReader = metadataReaderFactory.getMetadataReader(resource);
                     set.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
                 }
             }
         }
         if (!set.isEmpty()) {
             return set.toArray(new String[]{});
         } else {
             throw new MybatisPlusException("not find typeAliasesPackage:" + pkg);
         }
     } catch (Exception e) {
         throw new MybatisPlusException("not find typeAliasesPackage:" + pkg, e);
     }
 }
项目:mybatis-plus    文件:PackageHelper.java   
/**
  * <p>
  * 扫描获取指定包路径所有类
  * </p>
  *
  * @param typePackage 扫描类包路径
  * @return
  */
 public static Set<Class> scanTypePackage(String typePackage) {
     ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
     MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
     String pkg = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
             + ClassUtils.convertClassNameToResourcePath(typePackage) + "/*.class";
     /*
      * 将加载多个绝对匹配的所有Resource
* 将首先通过ClassLoader.getResource("META-INF")加载非模式路径部分,然后进行遍历模式匹配,排除重复包路径
*/
     try {
         Set<Class> set = new HashSet<>();
         Resource[] resources = resolver.getResources(pkg);
         if (resources != null && resources.length > 0) {
             MetadataReader metadataReader;
             for (Resource resource : resources) {
                 if (resource.isReadable()) {
                     metadataReader = metadataReaderFactory.getMetadataReader(resource);
                     set.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
                 }
             }
         }
         if (set.isEmpty()) {
             throw new MybatisPlusException("not find scanTypePackage:" + pkg);
         } else {
             return set;
         }
     } catch (Exception e) {
         throw new MybatisPlusException("not find scanTypePackage:" + pkg, e);
     }
 }
项目:jeesuite-libs    文件:TopicConsumerSpringProvider.java   
private void scanAndRegisterAnnotationTopics(String[] scanBasePackages){
    String RESOURCE_PATTERN = "/**/*.class";

    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    for (String scanBasePackage : scanBasePackages) {
        logger.info(">>begin scan package [{}] with Annotation[ConsumerHandler] MessageHanlder ",scanBasePackage);
        try {
               String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(scanBasePackage)
                       + RESOURCE_PATTERN;
               org.springframework.core.io.Resource[] resources = resourcePatternResolver.getResources(pattern);
               MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
               for (org.springframework.core.io.Resource resource : resources) {
                   if (resource.isReadable()) {
                       MetadataReader reader = readerFactory.getMetadataReader(resource);
                       String className = reader.getClassMetadata().getClassName();
                       Class<?> clazz = Class.forName(className);
                       if(clazz.isAnnotationPresent(ConsumerHandler.class)){
                        ConsumerHandler annotation = clazz.getAnnotation(ConsumerHandler.class);
                        MessageHandler hander = (MessageHandler) context.getBean(clazz);
                        if(!topicHandlers.containsKey(annotation.topic())){                             
                            topicHandlers.put(annotation.topic(), hander);
                            logger.info("register new MessageHandler:{}-{}",annotation.topic(),clazz.getName());
                        }
                       }
                   }
               }
               logger.info("<<scan package["+scanBasePackage+"] finished!");
           } catch (Exception e) {
            if(e instanceof org.springframework.beans.factory.NoSuchBeanDefinitionException){
                throw (org.springframework.beans.factory.NoSuchBeanDefinitionException)e;
            }
            logger.error("<<scan package["+scanBasePackage+"] error", e);
           }
    }

}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:EnableAutoConfigurationImportSelector.java   
private MetadataReaderFactory getMetadataReaderFactory() {
    try {
        return getBeanFactory().getBean(
                SharedMetadataReaderFactoryContextInitializer.BEAN_NAME,
                MetadataReaderFactory.class);
    }
    catch (NoSuchBeanDefinitionException ex) {
        return new CachingMetadataReaderFactory(this.resourceLoader);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:CloudAutoConfigurationTests.java   
@Test
public void testOrder() throws Exception {
    TestAutoConfigurationSorter sorter = new TestAutoConfigurationSorter(
            new CachingMetadataReaderFactory());
    Collection<String> classNames = new ArrayList<String>();
    classNames.add(MongoAutoConfiguration.class.getName());
    classNames.add(DataSourceAutoConfiguration.class.getName());
    classNames.add(MongoRepositoriesAutoConfiguration.class.getName());
    classNames.add(JpaRepositoriesAutoConfiguration.class.getName());
    classNames.add(CloudAutoConfiguration.class.getName());
    List<String> ordered = sorter.getInPriorityOrder(classNames);
    assertThat(ordered.get(0)).isEqualTo(CloudAutoConfiguration.class.getName());
}
项目:spring    文件:ConfigurationClassPostProcessor.java   
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
    this.beanClassLoader = beanClassLoader;
    if (!this.setMetadataReaderFactoryCalled) {
        this.metadataReaderFactory = new CachingMetadataReaderFactory(beanClassLoader);
    }
}
项目:spring-boot-concourse    文件:EnableAutoConfigurationImportSelector.java   
private MetadataReaderFactory getMetadataReaderFactory() {
    try {
        return getBeanFactory().getBean(
                SharedMetadataReaderFactoryContextInitializer.BEAN_NAME,
                MetadataReaderFactory.class);
    }
    catch (NoSuchBeanDefinitionException ex) {
        return new CachingMetadataReaderFactory(this.resourceLoader);
    }
}
项目:spring-boot-concourse    文件:CloudAutoConfigurationTests.java   
@Test
public void testOrder() throws Exception {
    TestAutoConfigurationSorter sorter = new TestAutoConfigurationSorter(
            new CachingMetadataReaderFactory());
    Collection<String> classNames = new ArrayList<String>();
    classNames.add(MongoAutoConfiguration.class.getName());
    classNames.add(DataSourceAutoConfiguration.class.getName());
    classNames.add(MongoRepositoriesAutoConfiguration.class.getName());
    classNames.add(JpaRepositoriesAutoConfiguration.class.getName());
    classNames.add(CloudAutoConfiguration.class.getName());
    List<String> ordered = sorter.getInPriorityOrder(classNames);
    assertThat(ordered.get(0)).isEqualTo(CloudAutoConfiguration.class.getName());
}
项目:herd    文件:ModelClassFinder.java   
/**
 * Finds all the model classes and the model error class.
 *
 * @throws MojoExecutionException if a class couldn't be instantiated or an I/O error occurred.
 */
private void findModelClasses() throws MojoExecutionException
{
    try
    {
        log.debug("Finding model classes.");

        // Get the model classes as resources.
        modelClasses = new HashSet<>();

        // Loop through each model resource and add each one to the set of model classes.
        for (Resource resource : ResourceUtils.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(modelJavaPackage)) +
            "/**/*.class"))
        {
            if (resource.isReadable())
            {
                MetadataReader metadataReader = new CachingMetadataReaderFactory(new PathMatchingResourcePatternResolver()).getMetadataReader(resource);
                Class<?> clazz = Class.forName(metadataReader.getClassMetadata().getClassName());
                modelClasses.add(clazz);
                log.debug("Found model class \"" + clazz.getName() + "\".");

                // If the model error class name is configured and matches this class, then hold onto it.
                if (clazz.getSimpleName().equals(modelErrorClassName))
                {
                    log.debug("Found model error class \"" + clazz.getName() + "\".");
                    modelErrorClass = clazz;
                }
            }
        }
    }
    catch (IOException | ClassNotFoundException e)
    {
        throw new MojoExecutionException("Error finding model classes. Reason: " + e.getMessage(), e);
    }
}
项目:wx_api    文件:ClassScaner.java   
/**
 * 设定 ResourceLoader
 * @param resourceLoader {@link ResourceLoader}
 */
public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourcePatternResolver = ResourcePatternUtils
            .getResourcePatternResolver(resourceLoader);  
    this.metadataReaderFactory = new CachingMetadataReaderFactory(  
            resourceLoader);  
}
项目:oldSyncopeIdM    文件:ConfigurationController.java   
@PreAuthorize("hasRole('CONFIGURATION_LIST')")
@RequestMapping(method = RequestMethod.GET,
value = "/mailTemplates")
public ModelAndView getMailTemplates() {
    CachingMetadataReaderFactory cachingMetadataReaderFactory =
            new CachingMetadataReaderFactory();

    Set<String> htmlTemplates = new HashSet<String>();
    Set<String> textTemplates = new HashSet<String>();

    try {
        for (Resource resource : resResolver.getResources(
                "classpath:/mailTemplates/*.vm")) {

            String template = resource.getURL().toExternalForm();
            if (template.endsWith(".html.vm")) {
                htmlTemplates.add(template.substring(
                        template.indexOf("mailTemplates/") + 14,
                        template.indexOf(".html.vm")));
            } else if (template.endsWith(".txt.vm")) {
                textTemplates.add(template.substring(
                        template.indexOf("mailTemplates/") + 14,
                        template.indexOf(".txt.vm")));
            } else {
                LOG.warn("Unexpected template found: {}, ignoring...",
                        template);
            }
        }
    } catch (IOException e) {
        LOG.error("While searching for class implementing {}",
                Validator.class.getName(), e);
    }

    // Only templates available both as HTML and TEXT are considered
    htmlTemplates.retainAll(textTemplates);

    return new ModelAndView().addObject(htmlTemplates);
}
项目:oldSyncopeIdM    文件:SpringPersistenceUnitPostProcessor.java   
@Override
public void postProcessPersistenceUnitInfo(
        final MutablePersistenceUnitInfo mpui) {

    if (locations.length == 0) {
        LOG.warn("No locations provided");
    }

    CachingMetadataReaderFactory cachingMetadataReaderFactory =
            new CachingMetadataReaderFactory();

    try {
        for (String location : locations) {
            for (Resource resource : resResolver.getResources(location)) {
                MetadataReader metadataReader =
                        cachingMetadataReaderFactory.getMetadataReader(
                        resource);
                if (metadataReader.getAnnotationMetadata().
                        isAnnotated(Entity.class.getName())) {

                    mpui.addManagedClassName(
                            metadataReader.getClassMetadata().
                            getClassName());
                }
            }
        }
        mpui.setExcludeUnlistedClasses(true);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}