我們常常有掃描項目里帶有指定注解的class, 下面是利用spring掃描自定義注解的方法, 還是比較靈活的
我這里將掃描到的class放到map, 你可以放到其他地方,以便后期使用
spring自己實現注解。import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
java自定義注解實現數據校驗,import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.Resource;
spring自定義注解切面、import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
Springboot注解,import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;
java自定義注解。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);
}
}
}
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态