您的位置:首页 > 编程语言 > Java开发

利用spring 自定义注解扫描 找出使用自定义注解的类

2018-03-08 00:00 253 查看
我们常常有扫描项目里带有指定注解的class, 下面是利用spring扫描自定义注解的方法, 还是比较灵活的

我这里将扫描到的class放到map, 你可以放到其他地方,以便后期使用

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
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 org.springframework.util.StringUtils;

import javax.persistence.Table;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
* 扫描指定包下带有指定注解的class
* @author jaffreyen
* @date 2018/3/5
*/
@Slf4j
public class MyApplicationListener implements ApplicationListener {

/**
* Handle an application event.
*
* @param event the event to respond to
*/
@Override
public void onApplicationEvent(ApplicationEvent event) {
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
final String RESOURCE_PATTERN = "/**/*.class";
// 扫描的包名
final String BASE_PACKAGE = "com.xxx";
Map<String,Class<?>> classCache = new HashMap<>();
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) {
if (resource.isReadable()) {
MetadataReader reader = readerFactory.getMetadataReader(resource);
//扫描到的class
String className = reader.getClassMetadata().getClassName();
Class<?> clazz = Class.forName(className);
//判断是否有指定注解
Table annotation = clazz.getAnnotation(Table.class);
if(annotation != null){
//这个类使用了自定义注解
classCache.put(className, clazz);
}
}
}
} catch (IOException | ClassNotFoundException e) {
log.error("读取class失败", e);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java EE