第11章 MetadataReader使用

在上一章中,看到了 MetadataReader 的身影,这一章就来学习 MetadataReader 方法,以便以后可以借助它快速地开发。

MetadataReader

MetadataReader 是用来读取 class 的元数据的类。

public interface MetadataReader {
    // Return the resource reference for the class file.
	Resource getResource();

    // Read basic class metadata for the underlying class.
	ClassMetadata getClassMetadata();

    // Read full annotation metadata for the underlying class, including metadata for annotated methods.
	AnnotationMetadata getAnnotationMetadata();

}

SimpleMetadataReader 是这个接口的实现,使用到 ASM 框架来读取class文件。

MetadataReaderFactory

工厂方法,用来创建 MetadataReaderFactory 对象。

public interface MetadataReaderFactory {
    
    MetadataReader getMetadataReader(String className) throws IOException; 
    
    MetadataReader getMetadataReader(Resource resource) throws IOException;
}

SimpleMetadataReaderFactoryCachingMetadataReaderFactory 都是这个接口实现类,用来创建 MetadataReader 对象。

使用

定义一个类

@Configuration
//@PropertySource(value = "classpath:/app.properties", name = "abc")
@ComponentScan(basePackages = "com.test", includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Animal.class))
public class AccountConfig {

	@Autowired
	Environment env;

	@Bean
	public People people() {
		System.out.println("===================");
		String[] defaultProfiles = env.getDefaultProfiles();
		Arrays.stream(defaultProfiles).forEach(System.out::println);
		System.out.println(env.getProperty("bean.name"));
		return new People();
	}
}
public static void main(String[] args) throws IOException {
		MetadataReaderFactory factory = new CachingMetadataReaderFactory();
		MetadataReader metadataReader = factory.getMetadataReader(AccountConfig.class.getName());

		ClassMetadata classMetadata = metadataReader.getClassMetadata();
		System.out.println(classMetadata.getClassName());
		System.out.println(classMetadata.getEnclosingClassName());
		if (classMetadata.getInterfaceNames().length != 0) {
			System.out.println(Arrays.asList(classMetadata.getInterfaceNames()));
		}
		if (classMetadata.getMemberClassNames().length != 0) {
			System.out.println(Arrays.asList(classMetadata.getMemberClassNames()));
		}
		System.out.println(classMetadata.getSuperClassName());

		System.out.println("==============================");

		AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
		System.out.println(annotationMetadata.getAnnotationTypes());
		System.out.println(annotationMetadata.hasAnnotation(Bean.class.getName()));
		System.out.println(annotationMetadata.hasAnnotation(Configuration.class.getName()));
	}
参考
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值