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

我们常常有扫描项目里带有指定注解的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> 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);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值