需求
获取spring项目里的带有某个注解的全部类
难点
需要扫描指定包路径下的类,同时也要扫描其下所有子包
思路
可以自己实现,推荐使用spring的工具类
代码
package com.example.demo;
import com.example.demo.annos.MyAnno;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ClassUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
private final String BASE_PACKAGE = "com.example.demo";
private final String RESOURCE_PATTERN = "/**/*.class";
@Test
public void test() {
Map<String, Class> handlerMap = new HashMap<String, Class>();
//spring工具类,可以获取指定路径下的全部类
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
try {
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE) + RESOURCE_PATTERN;
Resource[] resources = resourcePatternResolver.getResources(pattern);
//MetadataReader 的工厂类
MetadataReaderFactory readerfactory = new CachingMetadataReaderFactory(resourcePatternResolver);
for (Resource resource : resources) {
//用于读取类信息
MetadataReader reader = readerfactory.getMetadataReader(resource);
//扫描到的class
String classname = reader.getClassMetadata().getClassName();
Class<?> clazz = Class.forName(classname);
//判断是否有指定主解
MyAnno anno = clazz.getAnnotation(MyAnno.class);
if (anno != null) {
//将注解中的类型值作为key,对应的类作为 value
handlerMap.put(classname, clazz);
}
}
} catch (IOException | ClassNotFoundException e) {
}
}
}