SpringBoot中自定义扫描包并获取带有指定注解的类(注入IOC,非注入IOC容易的中)

//扫描没有注入IOC容器中的Bean
class Demo {
	//包下的类(这里扫描了所有)
    private final  static  String CLASS="*.class";
    
    //要扫描的包
    private final  static  String PACKAGE="com.demo.";
    

 /**
 扫描指定包并过滤带指定注解的类(非注入IOC中)
 */   
 public void initData() {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                ClassUtils.convertClassNameToResourcePath(PACKAGE) + CLASS;
        try {
            Resource[] resources = resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : resources) {
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                String classname = reader.getClassMetadata().getClassName();
                Class<?> clazz = Class.forName(classname);
                DataSubjectAnnotation dataSubjectAnnotation = clazz.getAnnotation(DataSubjectAnnotation.class);
                if (dataSubjectAnnotation != null) {
                    DataSubjectAnnotation annotation = clazz.getAnnotation(DataSubjectAnnotation.class);
                    subjectHashMap.put(annotation.type(), clazz);
                }
            }
        }catch (Exception e){
               e.printStackTrace();
        }

    }
}
//扫描注入IOC容器中的Bean
public class Demo  implements ApplicationListener<ApplicationContextEvent> {
    
    public HashMap<String, Class> subjectHashMap = new HashMap<>();
    
    //扫秒IOC容器中带有指定注解的类
    @Override
    public void onApplicationEvent(ApplicationContextEvent event) {
        ApplicationContext applicationContext =event.getApplicationContext();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(DataSubjectAnnotation.class);
        if(beansWithAnnotation !=null){
            beansWithAnnotation.forEach((key,value)->{
               String type= value.getClass().getAnnotation(DataSubjectAnnotation.class).type();
                subjectHashMap.put(type,value.getClass());
            });
        }
    }
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值