/** * <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; }
/** * 加载资源,根据resource获取className * * @param metadataReaderFactory spring中用来读取resource为class的工具 * @param resource 这里的资源就是一个Class * @throws IOException */ private static String loadClassName(MetadataReaderFactory metadataReaderFactory, Resource resource) throws IOException { try { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); if (metadataReader != null) { return metadataReader.getClassMetadata().getClassName(); } } } catch (Exception e) { LOG.error("根据resource获取类名称失败", e); } return null; }
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; }
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); } }
/** * 将符合条件的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; }
/** * 将符合条件的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; }
/** * 加载资源,根据resource获取className * * @param metadataReaderFactory * spring中用来读取resource为class的工具 * @param resource * 这里的资源就是一个Class * @throws IOException */ private static String loadClassName(MetadataReaderFactory metadataReaderFactory, Resource resource) throws IOException { try { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); if (metadataReader != null) { return metadataReader.getClassMetadata().getClassName(); } } } catch (Exception e) { log.error("根据resource获取类名称失败", e); } return null; }
/** * Configures parent scanner to search for the right interfaces. It can search * for all interfaces or just for those that extends a markerInterface or/and * those annotated with the annotationClass */ public void registerFilters() { if (Envs.classExists("org.n3r.eql.eqler.annotations.Eqler")) { addExcludeFilter(new AnnotationTypeFilter(Eqler.class)); addExcludeFilter(new AnnotationTypeFilter(EqlerConfig.class)); } addIncludeFilter(new TypeFilter() { @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory ) throws IOException { val metadata = metadataReader.getClassMetadata(); if (!metadata.isInterface()) return false; val className = metadata.getClassName(); val clazz = Envs.forName(className); return Anns.isFastWestCacheAnnotated(clazz); } }); }
@Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { if (isTestConfiguration(metadataReader)) { return true; } if (isTestClass(metadataReader)) { return true; } String enclosing = metadataReader.getClassMetadata().getEnclosingClassName(); if (enclosing != null) { try { if (match(metadataReaderFactory.getMetadataReader(enclosing), metadataReaderFactory)) { return true; } } catch (Exception ex) { // Ignore } } return false; }
private Set<AnnotationMetadata> findConfigurationClasses() throws IOException { Set<AnnotationMetadata> configurationClasses = new HashSet<AnnotationMetadata>(); Resource[] resources = this.resolver.getResources("classpath*:" + getClass().getPackage().getName().replace(".", "/") + "/**/*.class"); for (Resource resource : resources) { if (!isTestClass(resource)) { MetadataReader metadataReader = new SimpleMetadataReaderFactory() .getMetadataReader(resource); AnnotationMetadata annotationMetadata = metadataReader .getAnnotationMetadata(); if (annotationMetadata.getAnnotationTypes() .contains(Configuration.class.getName())) { configurationClasses.add(annotationMetadata); } } } return configurationClasses; }
protected List<String> getClasses(Resource[] resources) { List<String> classNames = new ArrayList<>(); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader metadataReader; try { metadataReader = metadataReaderFactory.getMetadataReader(resource); } catch (IOException e) { throw new RuntimeException("Unable to read metadata resource", e); } AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); if (annotationMetadata.isAnnotated(com.haulmont.chile.core.annotations.MetaClass.class.getName()) || annotationMetadata.isAnnotated(MappedSuperclass.class.getName()) || annotationMetadata.isAnnotated(Entity.class.getName())) { ClassMetadata classMetadata = metadataReader.getClassMetadata(); classNames.add(classMetadata.getClassName()); } } } return classNames; }
@Test public void getContextCustomizerShouldAddExcludeFilters() throws Exception { ContextCustomizer customizer = this.factory .createContextCustomizer(WithExcludeFilters.class, null); customizer.customizeContext(this.context, this.mergedContextConfiguration); this.context.refresh(); TypeExcludeFilter filter = this.context.getBean(TypeExcludeFilter.class); MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); MetadataReader metadataReader = metadataReaderFactory .getMetadataReader(NoAnnotation.class.getName()); assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse(); metadataReader = metadataReaderFactory .getMetadataReader(SimpleExclude.class.getName()); assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); metadataReader = metadataReaderFactory .getMetadataReader(TestClassAwareExclude.class.getName()); assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); }
private TypeExcludeFilter createDelegatingTypeExcludeFilter() { final Set<TypeExcludeFilter> filters = new LinkedHashSet<TypeExcludeFilter>( this.filterClasses.size()); for (Class<? extends TypeExcludeFilter> filterClass : this.filterClasses) { filters.add(createTypeExcludeFilter(filterClass)); } return new TypeExcludeFilter() { @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { for (TypeExcludeFilter filter : filters) { if (filter.match(metadataReader, metadataReaderFactory)) { return true; } } return false; } }; }
/** * <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); } }
protected boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException { try { Class<?> c = forName(metadataReader.getClassMetadata().getClassName()); if (c.getAnnotation(Configuration.class) != null) { return true; } } catch (Throwable e) { LOGGER.debug("error {}", e); } return false; }
/** * 检查当前扫描到的Bean含有任何一个指定的注解标记 * * @param reader * @param readerFactory * @return * @throws IOException */ private boolean matchesEntityTypeFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { if (!this.typeFilters.isEmpty()) { for (TypeFilter filter : this.typeFilters) { if (filter.match(reader, readerFactory)) { return true; } } } return false; }
public SourceClass(Object source) { this.source = source; if (source instanceof Class<?>) { this.metadata = new StandardAnnotationMetadata((Class<?>) source, true); } else { this.metadata = ((MetadataReader) source).getAnnotationMetadata(); } }
public Class<?> loadClass() throws ClassNotFoundException { if (this.source instanceof Class<?>) { return (Class<?>) this.source; } String className = ((MetadataReader) source).getClassMetadata().getClassName(); return resourceLoader.getClassLoader().loadClass(className); }
/** * Determine whether the given class is a candidate component based on any * {@code @Conditional} annotations. * @param metadataReader the ASM ClassReader for the class * @return whether the class qualifies as a candidate component */ private boolean isConditionMatch(MetadataReader metadataReader) { if (this.conditionEvaluator == null) { this.conditionEvaluator = new ConditionEvaluator(getRegistry(), getEnvironment(), getResourceLoader()); } return !this.conditionEvaluator.shouldSkip(metadataReader.getAnnotationMetadata()); }
/** * Check whether any of the configured entity type filters matches * the current class descriptor contained in the metadata reader. */ private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { for (TypeFilter filter : entityTypeFilters) { if (filter.match(reader, readerFactory)) { return true; } } return false; }
/** * Check whether any of the configured entity type filters matches * the current class descriptor contained in the metadata reader. */ private boolean matchesEntityTypeFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { for (TypeFilter filter : entityTypeFilters) { if (filter.match(reader, readerFactory)) { return true; } } return false; }
/** * Check whether any of the configured entity type filters matches * the current class descriptor contained in the metadata reader. */ private boolean matchesEntityTypeFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { if (this.entityTypeFilters != null) { for (TypeFilter filter : this.entityTypeFilters) { if (filter.match(reader, readerFactory)) { return true; } } } return false; }
public void registerDefaultFilters() { this.addIncludeFilter(new TypeFilter() { @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { return true; } }); }
/** * 检查当前扫描到的Bean含有任何一个指定的注解标记 * @param reader * @param readerFactory * @return * @throws IOException */ private boolean matchesEntityTypeFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { if (!this.typeFilters.isEmpty()) { for (TypeFilter filter : this.typeFilters) { if (filter.match(reader, readerFactory)) { return true; } } } return false; }
@Override public boolean isCandidateComponent(MetadataReader metadataReader) throws IOException { for(TypeFilter filter: includeFilters){ if(!filter.match(metadataReader, metadataReaderFactory)){ return false; } } return true; }
/** * 获取满足条件的所有的ClassMetadata * * @param basePackage * 基本的包含class的包, 如: "com.ilivoo,com.xiaosan" * @return */ private Set<ClassMetadata> findInterestClassMetadata(String basePackage) { List<Resource> allResource = findInterestResources(basePackage); Set<ClassMetadata> interests = new LinkedHashSet<ClassMetadata>(); for (Resource resource : allResource) { log.trace("扫描资源: " + resource); if (resource.isReadable()) { try { MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource); if (this.isCandidateComponent(metadataReader)) { interests.add(metadataReader.getClassMetadata()); } else { log.trace("资源不匹配TypeFilter: " + resource); } } catch (Throwable ex) { throw new BeanDefinitionStoreException("无法读取资源类: " + resource, ex); } } else { log.trace("忽略不可读的资源 : " + resource); } } return interests; }
@Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { if (this.beanFactory instanceof ListableBeanFactory && getClass().equals(TypeExcludeFilter.class)) { Collection<TypeExcludeFilter> delegates = ((ListableBeanFactory) this.beanFactory) .getBeansOfType(TypeExcludeFilter.class).values(); for (TypeExcludeFilter delegate : delegates) { if (delegate.match(metadataReader, metadataReaderFactory)) { return true; } } } return false; }
@Nonnull public static List<MetadataReader> getMetadataReaders( @Nonnull final String basePackage, @Nonnull final String requiredPathComponent) { return streamMetadataReaders(basePackage) .filter(getPathComponentPredicate(requiredPathComponent)) .collect(toList()); }
private static final Predicate<MetadataReader> getPathComponentPredicate(final String requiredPathComponent) { Objects.requireNonNull(requiredPathComponent); return input -> { try { return input.getResource().getFile().getAbsolutePath().toString() .replace("\\", "/") .contains(requiredPathComponent); } catch (final IOException e) { throw new RuntimeException(e); } }; }
public Class<?> loadClass() throws ClassNotFoundException { if (this.source instanceof Class<?>) { return (Class<?>) this.source; } String className = ((MetadataReader) this.source).getClassMetadata().getClassName(); return resourceLoader.getClassLoader().loadClass(className); }
@Test public void getMetadataReaderUsesCache() throws Exception { TestConcurrentReferenceCachingMetadataReaderFactory factory = spy( new TestConcurrentReferenceCachingMetadataReaderFactory()); MetadataReader metadataReader1 = factory.getMetadataReader(getClass().getName()); MetadataReader metadataReader2 = factory.getMetadataReader(getClass().getName()); assertThat(metadataReader1).isSameAs(metadataReader2); verify(factory, times(1)).createMetadataReader((Resource) any()); }
/** * Create a new {@link ConfigurationClass} with the given name. * @param metadataReader reader used to parse the underlying {@link Class} * @param beanName must not be {@code null} * @see ConfigurationClass#ConfigurationClass(Class, ConfigurationClass) */ public ConfigurationClass(MetadataReader metadataReader, String beanName) { Assert.hasText(beanName, "Bean name must not be null"); this.metadata = metadataReader.getAnnotationMetadata(); this.resource = metadataReader.getResource(); this.beanName = beanName; }
AutoConfigurationClasses(MetadataReaderFactory metadataReaderFactory, Collection<String> classNames) throws IOException { for (String className : classNames) { MetadataReader metadataReader = metadataReaderFactory .getMetadataReader(className); this.classes.put(className, new AutoConfigurationClass(metadataReader)); } }
@Override public MetadataReader getMetadataReader(Resource resource) throws IOException { MetadataReader metadataReader = this.cache.get(resource); if (metadataReader == null) { metadataReader = createMetadataReader(resource); this.cache.put(resource, metadataReader); } return metadataReader; }
@Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { String className = metadataReader.getClassMetadata().getClassName(); ResolvedType resolvedType = this.world.resolve(className); return this.typePattern.matchesStatically(resolvedType); }
@Test public void testDirectAnnotationMatch() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); String classUnderTest = "org.springframework.core.type.AnnotationTypeFilterTests$SomeComponent"; MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class); assertTrue(filter.match(metadataReader, metadataReaderFactory)); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); }
@Test public void testInheritedAnnotationFromInterfaceDoesNotMatch() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); String classUnderTest = "org.springframework.core.type.AnnotationTypeFilterTests$SomeSubClassOfSomeComponentInterface"; MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class); // Must fail as annotation on interfaces should not be considered a match assertFalse(filter.match(metadataReader, metadataReaderFactory)); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); }
@Test public void testNonInheritedAnnotationDoesNotMatch() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); String classUnderTest = "org.springframework.core.type.AnnotationTypeFilterTests$SomeSubclassOfSomeClassMarkedWithNonInheritedAnnotation"; MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AnnotationTypeFilter filter = new AnnotationTypeFilter(NonInheritedAnnotation.class); // Must fail as annotation isn't inherited assertFalse(filter.match(metadataReader, metadataReaderFactory)); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); }
@Test public void asmAnnotationMetadata() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(AnnotatedComponent.class.getName()); AnnotationMetadata metadata = metadataReader.getAnnotationMetadata(); doTestAnnotationInfo(metadata); doTestMethodAnnotationInfo(metadata); }