package com.**.handler;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Table;
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.util.ClassUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Test {
private final String BASE_PACKAGE = "com.xx.xx";
private final String RESOURCE_PATTERN = "/**/*.class";
public void main() {
Map<String, Class> handlerMap=new HashMap<String, Class>();
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
try {
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+
ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE)+ RESOURCE_PATTERN;
Resource[] resources =resourcePatternResolver.getResources(pattern);
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);
//判断是否有指定主解
Table anno = clazz.getAnnotation(Table.class);
if(anno != null) {
//将注解中的类型值作为key,对应的类作为 value
handlerMap.put(anno.name(), clazz);
log. info(anno.name()+"-"+clazz);
}
}
}catch(IOException | ClassNotFoundException e) {
log.error("读取 Handler失败",e);
}
}
}
Springboot扫描指定包中包含特定注解的类
最新推荐文章于 2024-04-29 17:13:56 发布