背景:
基于spring环境开发时,我们需要获取方法上注解,通常想到使用beanpostprocess去做,但是最近同事问我个问题,对于mybatis mapper接口上的自己的批量注解如何获取,这里提供一个方式获取指定包下的接口注解
CachingMetadataReaderFactory类属于org.springframework.core.type.classreading包
示例
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
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.CollectionUtils;
import java.util.*;
import java.util.stream.Collectors;
/**
* 初始化枚举选项类
* @Author 木林森
* @Date 2021/6/9
*/
@Configuration
public class LoadEnumOptions implements CommandLineRunner, ImportAware, ApplicationContextAware {
private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass());
private Set<String> locationPatterns = new HashSet<>();
private ApplicationContext applicationContext;
private static final Map<String, Options[]> map = new HashMap<>(32);
@Override
public void run(String... args) throws Exception {
log.info("======加载选项枚举类======");
for (String pattern : locationPatterns) {
String path = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(pattern) + "/**/*.class";
Resource[] resources = this.applicationContext.getResources(path);
MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(applicationContext);
for (Resource resource : resources) {
MetadataReader reader = metadataReaderFactory.getMetadataReader(resource);
String className = reader.getClassMetadata().getClassName();
Class<?> clazz = Class.forName(className);
if (Enum.class.isAssignableFrom(clazz) && Options.class.isAssignableFrom(clazz)) {
Options[] constants = (Options[]) clazz.getEnumConstants();
map.put(clazz.getSimpleName(), constants);
log.info("加载选项枚举类:" + clazz.getName());
}
}
}
log.info("======加载选项枚举类完毕======");
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> defaultAttrs = importMetadata.getAnnotationAttributes(EnableOptions.class.getName(), true);
String[] basePackage = (String[]) defaultAttrs.get("value");
Collections.addAll(locationPatterns, basePackage);
if (CollectionUtils.isEmpty(locationPatterns)) {
locationPatterns.add(ClassUtils.getPackageName(importMetadata.getClassName()));
}
}
/**
* 根据枚举类名获取枚举选项列表
* @param key
* @return
*/
public static List<Map<String, Object>> getEnumOptions(String key) {
Options[] options = map.get(key);
if(options == null || options.length < 1){
return Collections.emptyList();
}
return Arrays.stream(options)
.filter(e -> !e.isIgnore())
.sorted(Comparator.comparing(Options::getSort))
.map(e -> {
Map<String, Object> m = new HashMap<>(4);
m.put("value", e.getValue());
m.put("label", e.getDesc());
return m;
}).collect(Collectors.toList());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
获取指定包下的所有class文件