0
点赞
收藏
分享

微信扫一扫

第11章 MetadataReader使用

清冷的蓝天天 2022-03-27 阅读 60

在上一章中,看到了 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()));
	}

参考

  • Spring MetadataReader API
  • MetadataReaderFactory API
举报

相关推荐

0 条评论