实现注解相对于set注入和构造器注入是要麻烦一些的。但也有很多相似的地方。首先我们要解决的是怎么把一个包下的class扫描生成resource。具体的xml如下:
<context:component-scan base-package="org.litespring.service.v4,org.litespring.dao.v4">
</context:component-scan>
首先我们来写一个单元测试:
@Test
public void testGetResources() throws IOException{
PackageResourceLoader loader = new PackageResourceLoader();//扫描包
//把参数目录进行扫描,同时转成FileSystemResource,存放到Resource[size]里面。
Resource[] resources = loader.getResources("org.litespring.dao.v4");
System.out.println(resources.length);
Assert.assertEquals(2,resources.length);
}
根据测试用例可以看出来,我们需要一个PackageResourceLoader
类来解析我们的xml,把class转变成resource。
public class PackageResourceLoader {
private static final Log logger = LogFactory.getLog(PackageResourceLoader.class);
private final ClassLoader classLoader;
public PackageResourceLoader(){
this.classLoader = ClassUtils.getDefaultClassLoader();
}
/**
* 可以指定加载的classLoader
* @param classLoader
*/
public PackageResourceLoader(ClassLoader classLoader){
this.classLoader = classLoader;
}
/**
* 获取当前classLoader
* @return
*/
public ClassLoader getClassLoader() {
return this.classLoader;
}
/**
* 获取Resource[]
* @param basePackage 需要用到的包
* @return
* @throws IOException
*/
public Resource[] getResources(String basePackage)throws IOException{
Assert.notNull(basePackage , "basePackage must not be null ");
String location = ClassUtils.convertClassNameToResourcePath(basePackage);//对传入的目录进行字符串转换
ClassLoader cl = getClassLoader();//获取当前的classLoader
URL url = cl.getResource(location);//使用当前classLoader加载该目录
File rootDir = new File(url.getFile());//根据url,生成文件
//对文件进行遍历,可能传入的是多层文件夹,一层一层取出全部文件,存入到LinkedHashSet中
Set<File> matchingFiles = retrieveMatchingFiles(rootDir);
//创建matchingFiles大笑的Resource[]
Resource[] result = new Resource[matchingFiles.size()];
int i = 0 ;
//根据文件生成FileSystemResource
for (File file : matchingFiles){
result[i++] = new FileSystemResource(file);
}
return result;
}
/**
* 对文件进行遍历,可能传入的是多层文件夹,一层一层取出全部文件,存入到LinkedHashSet中
* @param rootDir 文件地址
* @return 返回全部文件Set
* @throws IOException
*/
protected Set<File> retrieveMatchingFiles(File rootDir)throws IOException{
if (!rootDir.exists()){
if (logger.isDebugEnabled()){
logger.debug("Skipping [" + rootDir.getAbsolutePath() + "] because it does not exist");
}
return Collections.emptySet();
}
if (!rootDir.isDirectory()){
if (logger.isWarnEnabled()){
logger.warn("Skipping [" + rootDir.getAbsolutePath() + "] because it does not denote a directory");
}
return Collections.emptySet();
}
if (!rootDir.canRead()){
if (logger.isWarnEnabled()){
logger.warn("Cannot search for matching files underneath directory [" + rootDir.getAbsolutePath()
+ "] because the application is not allowed to read the directory" );
}
return Collections.emptySet();
}
Set<File> result = new LinkedHashSet<File>(8);
//对该文件进行真正的取出
doRetrieveMatchingFiles(rootDir,result);
return result;
}
/**
* 取出全部文件
* @param dir
* @param result
* @throws IOException
*/
protected void doRetrieveMatchingFiles(File dir ,Set<File> result)throws IOException{
File[] dirContents = dir.listFiles();//得到该目录下全部文件
if (dirContents == null){//如果是空,则警告!!!
if (logger.isWarnEnabled()){
logger.warn("Could not retrieve contents of directory [" + dir.getAbsolutePath() + "]" );
}
return;
}
for (File content : dirContents){//进行遍历
if (content.isDirectory()){//如果是文件夹递归调用
if (!content.canRead()){
if (logger.isDebugEnabled()){
logger.debug("Skipping subdirectory [" + dir.getAbsolutePath() +
"] because the application is not allowed to read the directory");
}
}else {
doRetrieveMatchingFiles(content,result);
}
}else {//是文件则加入到result中
result.add(content);
}
}
}
}
这段代码简单的说就是遍历该目录,把目录下所有文件都转换成resource。由于扫描出来的resource过多,spring采用一种性能更好的方式进行解析,采用asm解析。Asm可以在运行期动态读取变更字节码。先给出代码,后面会解释asm的具体用法。下面是解析resource的测试用例
@Test
public void testGetClassMetaData()throws IOException{
//根据class生成resource
ClassPathResource resource = new ClassPathResource("org/litespring/service/v4/PetStoreService.class");
//通过classReader读取字节流
ClassReader reader = new ClassReader(resource.getInputStream());
//实现自己的Vistitor为了让Asm把解析好的类通过ClassReader回调Vistitor的方式通知我们
ClassMetadataReadingVisitor visitor = new ClassMetadataReadingVisitor();
//ClassReader回调创建的这个visitor
reader.accept(visitor , ClassReader.SKIP_DEBUG);
Assert.assertFalse(visitor.isAbstract());
Assert.assertFalse(visitor.isInterface());
Assert.assertFalse(visitor.isFinal());
Assert.assertEquals("org.litespring.service.v4.PetStoreService", visitor.getClassName());
Assert.assertEquals("java.lang.Object", visitor.getSuperClassName());
Assert.assertEquals(0, visitor.getInterfaceNames().length);
}
asm实际上是访问者(visitor)模式,把上面扫描生成的resource传递给Asm框架的ClassReader进行解析,每当解析好了就调用咱们写的ClassMetadataReadingVisitor的visitor方法。asm的jar包上传到git上了。接下来我们看一下ClassMetadataReadingVisitor的具体实现吧。
public class ClassMetadataReadingVisitor extends ClassVisitor {
private String className;
private boolean isInterface;
private boolean isAbstract;
private boolean isFinal;
private String superClassName;
private String[] interfaces;
public ClassMetadataReadingVisitor() {
super( SpringAsmInfo.ASM_VERSION);
}
/**
* classReader回掉的方法
* @param version
* @param access
* @param name
* @param signature
* @param supername
* @param interfaces
*/
public void visit(int version, int access, String name, String signature, String supername, String[] interfaces) {
this.className = ClassUtils.convertResourcePathToClassName(name);//获取className
this.isInterface = ((access & Opcodes.ACC_INTERFACE) != 0);//获取接口
this.isAbstract = ((access & Opcodes.ACC_ABSTRACT) != 0);//是否是抽象的
this.isFinal = ((access & Opcodes.ACC_FINAL) != 0);//是否是Final
if (supername != null) {//父类不为空
this.superClassName = ClassUtils.convertResourcePathToClassName(supername);
}
this.interfaces = new String[interfaces.length];
for (int i = 0; i < interfaces.length; i++) {
this.interfaces[i] = ClassUtils.convertResourcePathToClassName(interfaces[i]);
}
}
public String getClassName() {
return this.className;
}
public boolean isInterface() {
return this.isInterface;
}
public boolean isAbstract() {
return this.isAbstract;
}
public boolean isConcrete() {
return !(this.isInterface || this.isAbstract);
}
public boolean isFinal() {
return this.isFinal;
}
public boolean hasSuperClass() {
return (this.superClassName != null);
}
public String getSuperClassName() {
return this.superClassName;
}
public String[] getInterfaceNames() {
return this.interfaces;
}
}
上面的测试用例是通过asm解析给定的java类,可以成功解析出内容,接下来我们来解析java类的注解内容。接下来我给出测试用例:
public void testGetAnnonation() throws Exception{
ClassPathResource resource = new ClassPathResource("org/litespring/service/v4/PetStoreService.class");
ClassReader reader = new ClassReader(resource.getInputStream());
//注解的visitor
AnnotationMetadataReadingVisitor visitor = new AnnotationMetadataReadingVisitor();
reader.accept(visitor, ClassReader.SKIP_DEBUG);
String annotation = "org.litespring.stereotype.Component";
//判断vistor取得的注解
Assert.assertTrue(visitor.hasAnnotation(annotation));
//获取vistor取得注解的实体
AnnotationAttributes attributes = visitor.getAnnotationAttributes(annotation);
Assert.assertEquals("petStore", attributes.get("value"));
}
这里为了解析注解,用到了一个新的类AnnotationMetadataReadingVisitor
重写了 visitAnnotation
方法:
public class AnnotationMetadataReadingVisitor extends ClassMetadataReadingVisitor {
private final Set<String> annotationSet = new LinkedHashSet<>(4);
private final Map<String, AnnotationAttributes> attributeMap = new LinkedHashMap<String, AnnotationAttributes>(4);
public AnnotationMetadataReadingVisitor() {
}
@Override
public AnnotationVisitor visitAnnotation(final String desc, boolean visible) {
String className = Type.getType(desc).getClassName();//获取注解类
this.annotationSet.add(className);
return new AnnotationAttributesReadingVisitor(className, this.attributeMap);
}
public Set<String> getAnnotationTypes() {
return this.annotationSet;
}
public boolean hasAnnotation(String annotationType) {
return this.annotationSet.contains(annotationType);
}
public AnnotationAttributes getAnnotationAttributes(String annotationType) {
return this.attributeMap.get(annotationType);
}
}
实现以上便可以运行成功上述的测试用例了。而日常的开发让我们使用这么底层的东西其实是不太好的。我们需要对它进一步的封装,这里抽象出来了三个接口MetadataReader、ClassMetadata、AnnotationMetadata,让原有ClassMetadataReadingVisitor实现ClassMetaData,AnnotationMetadataReadingVisitor实现AnnotationMetadata,同时实现一个SimpleMetadataReader实现MetadataReader,以后只需要使用MetadataXXX类就可以了。具体的代码查看litespring_07
生活要多点不自量力
网友评论