/** * <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; }
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; } }; }
@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(); }
@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); } }
@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; }
/** * <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); } }
/** * 根据扫描包的,查询下面的所有类 * * @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; }
/** * 检查当前扫描到的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; }
/** * Create a new {@link ConfigurationClassParser} instance that will be used * to populate the set of configuration classes. */ public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory, ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader, BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) { this.metadataReaderFactory = metadataReaderFactory; this.problemReporter = problemReporter; this.environment = environment; this.resourceLoader = resourceLoader; this.registry = registry; this.componentScanParser = new ComponentScanAnnotationParser( resourceLoader, environment, componentScanBeanNameGenerator, registry); this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader); }
/** * Create a new {@link ConfigurationClassBeanDefinitionReader} instance that will be used * to populate the given {@link BeanDefinitionRegistry}. */ public ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor, ProblemReporter problemReporter, MetadataReaderFactory metadataReaderFactory, ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator) { this.registry = registry; this.sourceExtractor = sourceExtractor; this.problemReporter = problemReporter; this.metadataReaderFactory = metadataReaderFactory; this.resourceLoader = resourceLoader; this.environment = environment; this.importBeanNameGenerator = importBeanNameGenerator; this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader); }
/** * 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; }
/** * 根据扫描包的,查询下面的所有类 * * @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; }
@Test public void customRequestScopeViaAsm() throws IOException { MetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory(); MetadataReader reader = readerFactory.getMetadataReader(AnnotatedWithCustomRequestScope.class.getName()); AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(reader.getAnnotationMetadata()); ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); assertEquals("request", scopeMetadata.getScopeName()); assertEquals(NO, scopeMetadata.getScopedProxyMode()); }
/** * Check whether any of the configured entity type filters matches * the current class descriptor contained in the metadata reader. */ protected boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { for (TypeFilter filter : ENTITY_TYPE_FILTERS) { if (filter.match(reader, readerFactory)) { return true; } } return false; }
@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); }
@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; }
@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); }
AutoConfigurationClasses(MetadataReaderFactory metadataReaderFactory, Collection<String> classNames) throws IOException { for (String className : classNames) { MetadataReader metadataReader = metadataReaderFactory .getMetadataReader(className); this.classes.put(className, new AutoConfigurationClass(metadataReader)); } }
@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 testMatchesInterfacesIfConfigured() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); String classUnderTest = "org.springframework.core.type.AnnotationTypeFilterTests$SomeComponentInterface"; MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class, false, true); assertTrue(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); }
@Test public void asmAnnotationMetadataForSubclass() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(AnnotatedComponentSubClass.class.getName()); AnnotationMetadata metadata = metadataReader.getAnnotationMetadata(); doTestSubClassAnnotationInfo(metadata); }
@Test public void asmAnnotationMetadataForInterface() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(AnnotationMetadata.class.getName()); AnnotationMetadata metadata = metadataReader.getAnnotationMetadata(); doTestMetadataForInterfaceClass(metadata); }
@Test public void asmAnnotationMetadataForAnnotation() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(Component.class.getName()); AnnotationMetadata metadata = metadataReader.getAnnotationMetadata(); doTestMetadataForAnnotationClass(metadata); }