Java CachingMetadataReaderFactory类代码示例

背景:

基于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文件
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值