首页 > 其他分享 >Spring 高级 工厂后处理器模拟实现组件扫描-模拟ComponentScan 进阶

Spring 高级 工厂后处理器模拟实现组件扫描-模拟ComponentScan 进阶

时间:2022-08-22 21:45:54浏览次数:73  
标签:进阶 Spring factory springframework context import org class 模拟

一、自定义Bean 后处理器 Processor

package com.mangoubiubiu.show.a05.component;

import com.mangoubiubiu.show.a05.Config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.stereotype.Component;

import java.io.IOException;

public class ComponentScanPostProcessor implements BeanFactoryPostProcessor {

    /**
     * context.refresh   初始化ApplicationContext的时候会回调这个方法
     * @param configurableListableBeanFactory
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

        try {

            //Spring工具类 读取类的源信息
            CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
            //查找某个类上有没有加注解 第一个参数 某个类的类型  第二个参数 要找的注解
            ComponentScan componentScan = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);
            if(componentScan!=null){
                for (String p:componentScan.basePackages()) {
                    System.out.println("包名:"+p);


                    AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();

                    //com.mangoubiubiu.show.a05.component
                    StringBuilder path = new StringBuilder();
                    path.append("classpath*:").append(p.replace(".","/")).append("/**/*.class");
                    System.out.println("拼接后的包名:"+path.toString());
                    //读取路径下的文件
                    Resource[] resources = new PathMatchingResourcePatternResolver().getResources(path.toString());
                    for (Resource res:resources) {
                        System.out.println("读取到的文件信息为:"+res);
                        MetadataReader reader = factory.getMetadataReader(res);
                        System.out.println("得到类信息:"+ reader.getClassMetadata().getClassName());
                        AnnotationMetadata annotationMetadata = reader.getAnnotationMetadata();
                        System.out.println("是否加了Component注解"+ annotationMetadata.hasAnnotation(Component.class.getName()));
                        System.out.println("是否加了Component注解 派生"+ annotationMetadata.hasMetaAnnotation(Component.class.getName()));

                        if(annotationMetadata.hasAnnotation(Component.class.getName()) || annotationMetadata.hasMetaAnnotation(Component.class.getName())){
                            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(reader.getClassMetadata().getClassName()).getBeanDefinition();

                            if (configurableListableBeanFactory instanceof DefaultListableBeanFactory  ) {
                                DefaultListableBeanFactory beanFactory = ((DefaultListableBeanFactory) configurableListableBeanFactory);
                                String beanName = generator.generateBeanName(beanDefinition, beanFactory);
                                beanFactory.registerBeanDefinition(beanName,beanDefinition);
                            }
                        }


                    }


                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

二、将ComponentScanPostProcessor 注入到容器里面

package com.mangoubiubiu.show.a05;

import com.mangoubiubiu.show.a05.component.ComponentScanPostProcessor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.io.IOException;

@Slf4j
public class A05Application {

    private MetadataReader reader;

    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        //将config注册到容器里面
        context.registerBean("config",Config.class);
        context.registerBean(ComponentScanPostProcessor.class);
//        context.registerBean(MapperScannerConfigurer.class,beanDefinition -> {
//            beanDefinition.getPropertyValues().add("basePackage","com.mangoubiubiu.show.a05.mapper");
//        });



        //初始化容器

        context.refresh();

        for (String name: context.getBeanDefinitionNames()) {
            System.out.println(name);
        }

        context.close();
    }



}

 

可以看到在Config类上面配了包扫描,指定包下标注了@Component或者@Controller的bean 被我们成功扫描进IOC容器里面。

 

 

 

标签:进阶,Spring,factory,springframework,context,import,org,class,模拟
From: https://www.cnblogs.com/mangoubiubiu/p/16614352.html

相关文章

  • Spring 循环依赖引起 This is very likely to create a memory leak 问题
    背景:在公司测试环境发布测试的时候,发布失败了。日志报错:Thisisverylikelytocreateamemoryleak 。但是奇怪的是我的本地idea是启动正常的。没问题的。然后就跟运维......
  • springboot使用@Async实现异步调用
    异步与同步同步就是整个处理过程顺序执行,当各个过程都执行完毕,并返回结果。异步调用则是只是发送了调用的指令,调用者无需等待被调用的方法完全执行完毕;而是继续执行......
  • 3.springboot和springcloud alibaba版本问题
    启动项目报错Causedby:java.lang.ClassNotFoundException:...boot.context.properties.ConfigurationPropertiesBean 解决办法:我的springboot用的<parent>......
  • java springboot 初体验 (七)对接链路追踪
    上一篇javaspringboot初体验(六)添加统一的入参出参打印日志(使用切面)https://www.cnblogs.com/zwjvzwj/p/16612094.htmlMDC介绍MDC(MappedDiagnosticContext,映射......
  • springMVC01 配置
    1.配置流程1.1配置前端控制器,对浏览器请求统一处理1.2配置springMVC的配置文件路径1.3启动改为服务器启动时  <?xmlversion="1.0"encoding="UTF-8"?><web-......
  • SpringMVC-入门
    第一章初识SpringMVC1.1SpringMVC概述SpringMVC是Spring子框架,是Spring为展现层提供的基于MVC设计理念的优秀的Web框架SpringMVC通过一套MVC注解,让POJO成为......
  • SpringBoot中的事务
    [转]https://www.cnblogs.com/l-liu/p/16169399.html 一、说明介绍①使用事务,我们只需要在需要事务的类或方法上使用@Transactional注解即可,当注解在类上的时候意味着此......
  • SpringMvc学习笔记博文转发
    学习笔记博文1:SpringMVC学习笔记学习笔记博文2:SpringMVC的学习笔记(整合)学习笔记博文3:SpringMVC学习笔记......
  • java springboot 初体验 (六)添加统一的入参出参打印日志(使用切面)
    上一篇javaspringboot初体验(五)对接apollohttps://www.cnblogs.com/zwjvzwj/p/16602858.htmlpom文件中添加依赖<!--切面--><dependency>......
  • 转发两篇优秀Spring学习笔记博文
    博文1:Spring学习笔记1 博文2:Spring学习笔记2......