public class ReadAnnotationUtils {
private static final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
private static final SimpleMetadataReaderFactory register = new SimpleMetadataReaderFactory();
private static final StandardEnvironment environment = new StandardEnvironment();
public static String getResourcePath(String packagePath) {
if (StringUtils.isEmpty(packagePath)) return "";
String resourcePath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+ ClassUtils.convertClassNameToResourcePath(environment.resolveRequiredPlaceholders(packagePath))
+ '/' + "**
public static Set getClazzFromAnnotation(String pkgPath, Class extends Annotation> annoClazz) {
//获取spring的包路径
String pathPackage = getResourcePath(pkgPath);
Set paths = new HashSet<>();
Resource[] resources = new Resource[0];
try {
//加载路径
resources = resolver.getResources(pathPackage);
} catch (IOException e) {
//异常处理
return new HashSet<>();
}
for (int i = 0; i < resources.length; i++) {
Resource resource = resources[i];
MetadataReader metadataReader = null;
try {
//读取资源
metadataReader = register.getMetadataReader(resource);
} catch (IOException e) {
continue;
}
//读取资源的注解配置
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
//判断是否包含注解
if (!annotationMetadata.hasAnnotation(annoClazz.getName())) continue;
//类信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
//类全名
String className = classMetadata.getClassName();
try {
//加载类
Class> clazz = Class.forName(className);
paths.add(clazz);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return paths;
}
public static void main(String[] args) {
//测试
Set clazz = getClazzFromAnnotation("com.pkg.fp", RSPI.class);
System.out.println(clazz);
}
}