org.springframework.core.type.classreading.MetadataReaderFactory Java Examples

The following examples show how to use org.springframework.core.type.classreading.MetadataReaderFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransactionalServiceAnnotationMetadataBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    // @TransactionalService 标注在当前类 TransactionalServiceAnnotationMetadataBootstrap
    String className = TransactionalServiceAnnotationMetadataBootstrap.class.getName();
    // 构建 MetadataReaderFactory 实例
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();
    // 读取 @TransactionService MetadataReader 信息
    MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
    // 读取 @TransactionService AnnotationMetadata 信息
    AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();

    annotationMetadata.getAnnotationTypes().forEach(annotationType -> {

        Set<String> metaAnnotationTypes = annotationMetadata.getMetaAnnotationTypes(annotationType);

        metaAnnotationTypes.forEach(metaAnnotationType -> {
            System.out.printf("注解 @%s 元标注 @%s\n", annotationType, metaAnnotationType);
        });

    });
}
 
Example #2
Source File: DataSourceAutoConfiguration.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Let typeAliasesPackage alias bean support wildcards.
 * 
 * @return
 */
private Class<?>[] getTypeAliases(PathMatchingResourcePatternResolver resolver) throws Exception {
	List<Class<?>> typeAliases = new ArrayList<>();

	// Define metadataReader
	MetadataReaderFactory metadataReaderFty = new CachingMetadataReaderFactory(resolver);

	for (String pkg : typeAliasesPackage.split(",")) {
		// Get location
		String location = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg)
				+ "**/*.class";
		// Get resources.
		Resource[] resources = resolver.getResources(location);
		if (resources != null) {
			for (Resource resource : resources) {
				if (resource.isReadable()) {
					MetadataReader metadataReader = metadataReaderFty.getMetadataReader(resource);
					typeAliases.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
				}
			}
		}
	}

	return typeAliases.toArray(new Class<?>[] {});
}
 
Example #3
Source File: MyTypeFilter.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 自定义包扫描过滤规则
 *
 * @param metadataReader 读取到当前正在扫描的类的信息
 * @param metadataReaderFactory 获取其他任何类型
 * @return boolean
 */
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
    // 获取当前正在扫描的类注解的信息
    AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
    // 获取当前正在扫描的类的信息
    ClassMetadata classMetadata = metadataReader.getClassMetadata();
    // 获取类名
    String className = classMetadata.getClassName();
    System.out.println("扫描的类——》" + className);
    // 根据类名进行过滤
    if (className.contains("Book")) {
        return true;
    }
    // 证明filter在Conditional之前拦截
    //Annotation[] annotations = classMetadata.getClass().getAnnotations();
    //for (Annotation annotation : annotations) {
    //    if (annotation.annotationType() == Conditional.class) {
    //        return false;
    //    }
    //}
    //return true;
    return false;
}
 
Example #4
Source File: AspectJTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void assertNoMatch(String type, String typePattern) throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type);

	AspectJTypeFilter filter = new AspectJTypeFilter(typePattern, getClass().getClassLoader());
	assertFalse(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(type);
}
 
Example #5
Source File: AnnotationTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testMatchesInterfacesIfConfigured() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AnnotationTypeFilterTests$SomeClassWithSomeComponentInterface";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class, false, true);
	assertTrue(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
 
Example #6
Source File: AnnotationTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example #7
Source File: AnnotationMetadataTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void asmAnnotationMetadataForAnnotation() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(Component.class.getName());
	AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
	doTestMetadataForAnnotationClass(metadata);
}
 
Example #8
Source File: AssignableTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void interfaceThroughSuperClassMatch() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AssignableTypeFilterTests$SomeDaoLikeImpl";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AssignableTypeFilter filter = new AssignableTypeFilter(JdbcDaoSupport.class);
	assertTrue(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
 
Example #9
Source File: AssignableTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void superClassMatch() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AssignableTypeFilterTests$SomeDaoLikeImpl";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AssignableTypeFilter filter = new AssignableTypeFilter(SimpleJdbcDaoSupport.class);
	assertTrue(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
 
Example #10
Source File: AssignableTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void interfaceMatch() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AssignableTypeFilterTests$TestInterfaceImpl";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AssignableTypeFilter filter = new AssignableTypeFilter(TestInterface.class);
	assertTrue(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
 
Example #11
Source File: AssignableTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void directMatch() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AssignableTypeFilterTests$TestNonInheritingClass";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AssignableTypeFilter matchingFilter = new AssignableTypeFilter(TestNonInheritingClass.class);
	AssignableTypeFilter notMatchingFilter = new AssignableTypeFilter(TestInterface.class);
	assertFalse(notMatchingFilter.match(metadataReader, metadataReaderFactory));
	assertTrue(matchingFilter.match(metadataReader, metadataReaderFactory));
}
 
Example #12
Source File: AnnotationMetadataTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * https://jira.spring.io/browse/SPR-11649
 */
@Test
public void composedAnnotationWithMetaAnnotationsWithIdenticalAttributeNamesUsingAnnotationMetadataReadingVisitor() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(NamedComposedAnnotationClass.class.getName());
	AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
	assertMultipleAnnotationsWithIdenticalAttributeNames(metadata);
}
 
Example #13
Source File: AnnotationMetadataTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * https://jira.spring.io/browse/SPR-11649
 */
@Test
public void multipleAnnotationsWithIdenticalAttributeNamesUsingAnnotationMetadataReadingVisitor() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(NamedAnnotationsClass.class.getName());
	AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
	assertMultipleAnnotationsWithIdenticalAttributeNames(metadata);
}
 
Example #14
Source File: AnnotationMetadataTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void metaAnnotationOverridesUsingAnnotationMetadataReadingVisitor() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(ComposedConfigurationWithAttributeOverridesClass.class.getName());
	AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
	assertMetaAnnotationOverrides(metadata);
}
 
Example #15
Source File: AnnotationTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example #16
Source File: AnnotationTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testNonAnnotatedClassDoesntMatch() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AnnotationTypeFilterTests$SomeNonCandidateClass";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AnnotationTypeFilter filter = new AnnotationTypeFilter(Component.class);
	assertFalse(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
 
Example #17
Source File: LocalSessionFactoryBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #18
Source File: DefaultPersistenceUnitManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #19
Source File: AspectJTypeFilter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example #20
Source File: AnnotationScopeMetadataResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void customRequestScopeWithAttributeViaAsm() throws IOException {
	MetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory();
	MetadataReader reader = readerFactory.getMetadataReader(AnnotatedWithCustomRequestScopeWithAttributeOverride.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(TARGET_CLASS, scopeMetadata.getScopedProxyMode());
}
 
Example #21
Source File: AnnotationScopeMetadataResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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());
}
 
Example #22
Source File: LocalSessionFactoryBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source File: PackagesSqlSessionFactoryBean.java    From spring-boot-api-project-seed with Apache License 2.0 5 votes vote down vote up
@Override
public void setTypeAliasesPackage(String typeAliasesPackage) {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
    typeAliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            ClassUtils.convertClassNameToResourcePath(typeAliasesPackage) + "/" + DEFAULT_RESOURCE_PATTERN;

    //将加载多个绝对匹配的所有Resource
    //将首先通过ClassLoader.getResource("META-INF")加载非模式路径部分
    //然后进行遍历模式匹配
    try {
        List<String> result = new ArrayList<>();
        Resource[] resources = resolver.getResources(typeAliasesPackage);
        if (resources.length > 0) {
            MetadataReader metadataReader = null;
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
                }
            }
        }
        if (!result.isEmpty()) {
            super.setTypeAliasesPackage(StringUtils.join(result.toArray(), ","));
        } else {
            String msg = String.format("参数typeAliasesPackage:%s,未找到任何包", typeAliasesPackage);
            logger.warn(msg);
        }
    } catch (IOException | ClassNotFoundException e) {
        logger.info(e.getMessage());
    }
}
 
Example #24
Source File: ClassPathJaxb2TypeScanner.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected boolean isJaxb2Class(MetadataReader reader, MetadataReaderFactory factory) throws IOException {
	for (TypeFilter filter : JAXB2_TYPE_FILTERS) {
		if (filter.match(reader, factory) && !reader.getClassMetadata().isInterface() ) {
			return true;
		}
	}
	return false;
}
 
Example #25
Source File: FunctionalInstallerImportRegistrars.java    From spring-init with Apache License 2.0 5 votes vote down vote up
public FunctionalInstallerImportRegistrars(GenericApplicationContext context) {
	this.context = context;
	String metadataFactory = MetadataReaderFactory.class.getName();
	this.metadataReaderFactory = context.getBeanFactory().containsSingleton(metadataFactory)
			? (MetadataReaderFactory) context.getBeanFactory().getSingleton(metadataFactory)
			: new CachingMetadataReaderFactory(context.getClassLoader());
}
 
Example #26
Source File: ConfigurationClassParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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(
			environment, resourceLoader, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #27
Source File: ConfigurationClassParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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(
			environment, resourceLoader, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #28
Source File: RpcDefinitionPostProcessor.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) {
    ClassMetadata classMetadata = metadataReader.getClassMetadata();
    if (classMetadata.isConcrete() && !classMetadata.isAnnotation()) {
        //找到类
        Class<?> clazz = resolveClassName(classMetadata.getClassName(), classLoader);
        //判断是否Public
        if (Modifier.isPublic(clazz.getModifiers())) {
            Class<?> targetClass = clazz;
            while (targetClass != null && targetClass != Object.class) {
                //处理类上的服务提供者注解
                if (getProviderAnnotation(targetClass) != null) {
                    return true;
                }
                //处理字段的消费者注解
                for (Field field : targetClass.getDeclaredFields()) {
                    if (!Modifier.isFinal(field.getModifiers())
                            && !Modifier.isStatic(field.getModifiers())
                            && getConsumerAnnotation(field) != null) {
                        return true;
                    }
                }
                //处理方法上的消费者注解
                for (Method method : clazz.getDeclaredMethods()) {
                    if (!Modifier.isStatic(method.getModifiers())
                            && Modifier.isPublic(method.getModifiers())
                            && method.getParameterCount() == 1
                            && method.getName().startsWith("set")
                            && getConsumerAnnotation(method) != null) {
                        return true;
                    }
                }
                targetClass = targetClass.getSuperclass();
            }

        }
    }
    return false;
}
 
Example #29
Source File: ClassPathJaxb2TypeScanner.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected boolean isJaxb2Class(MetadataReader reader, MetadataReaderFactory factory) throws IOException {
	for (TypeFilter filter : JAXB2_TYPE_FILTERS) {
		if (filter.match(reader, factory) && !reader.getClassMetadata().isInterface() ) {
			return true;
		}
	}
	return false;
}
 
Example #30
Source File: AspectJTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void assertMatch(String type, String typePattern) throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type);

	AspectJTypeFilter filter = new AspectJTypeFilter(typePattern, getClass().getClassLoader());
	assertTrue(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(type);
}