栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring2-b站黑马

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring2-b站黑马

019-第五讲-常见工厂后处理器 019-1

Bean1.class

@Slf4j
public class Bean1 {
    public Bean1() {
      log.info("我被 Spring 管理了 ");
    }
}

Bean2.class

@Component
@Slf4j
public class Bean2 {
    public Bean2() {
        log.info("我被 Spring 管理了 ");
    }
}

Config.class

@Configuration
@ComponentScan("com.zdjx.springdemo.component")
public class Config {

    @Bean
    public Bean1 bean1(){return new Bean1();}

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean(initMethod = "init")
    public DruidDataSource dataSource() throws SQLException {
       DruidDataSource dataSource = new DruidDataSource();
       dataSource.setUrl("jdbc:mysql://localhost:3306/test");
       dataSource.setUsername("root");
       dataSource.setPassword("root");
       dataSource.setDriver(new com.mysql.jdbc.Driver());
       return dataSource;
    }
}

POM.xml


        com.baomidou
		mybatis-plus-boot-starter
		3.2.0



		com.alibaba
		druid
		1.2.3



		mysql
		mysql-connector-java

TestMain.java

@Slf4j
public class TestMain {
    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config", Config.class);

        //初始化容器
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        //销毁容器
        context.close();
    }
}

运行

019-2

可以看到这里只有一个  Config 加入了容器中 , 所以@ComponetScan @Bean注解并未生效.

另外还能解析 @Import 和 @ImportResource注解

所以

增加beanFactoryPostProcessor

ConfigurationClassPostProcessor.class//赋予解析 @ComponentScan 和 @Bean注解

 TestMain.java

@Slf4j
public class TestMain {
    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config", Config.class);
        context.registerBean(ConfigurationClassPostProcessor.class);

        //初始化容器
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        //销毁容器
        context.close();
    }
}

运行

成功解析了 @ComponentScan 和 @Bean

019-3 beanFactory后处理器-扫描mapper接口

Mapper1.interface

@Mapper
public interface Mapper1 {
}

Mapper2.interface

@Mapper
public interface Mapper2 {
}

增加解析@Mapper 将Dao接口放入容器的功能

context.registerBean(MapperScannerConfigurer.class,
                beanDefinition ->
                        beanDefinition.getPropertyValues().add("basePackage","com.zdjx.springdemo.mapper")
                ); //与@MapperScan功能一样

TestMain.java

@Slf4j
public class TestMain {
    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config", Config.class);
        context.registerBean(ConfigurationClassPostProcessor.class);
        context.registerBean(MapperScannerConfigurer.class,
                beanDefinition ->
                        beanDefinition.getPropertyValues().add("basePackage","com.zdjx.springdemo.mapper")
                ); //与@MapperScan功能一样 , 根据提供的basePackage 解析 mapper接口

        //初始化容器
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        //销毁容器
        context.close();
    }
}

运行

020-第五讲-工厂后处理器模拟实现-组件扫描 020-1 模拟@ComponentScan注解的解析

Bean1.java

@Slf4j
public class Bean1 {
    public Bean1() {
      log.info("我被 Spring 管理了 ");
    }
}

Bean2.java

@Component
@Slf4j
public class Bean2 {
    public Bean2() {
        log.info("我被 Spring 管理了 ");
    }
}

Bean3.java

@Component
@Slf4j
public class Bean3 {
    public Bean3() {
        log.info("我被 Spring 管理了 ");
    }
}

Bean4.java

@Slf4j
public class Bean4 {
    public Bean4() {
        log.info("我被 Spring 管理了 ");
    }
}

模拟@ComponentScan

 
        //AnnotationUtils => Spring提供的工具类 , 查找某个类上是否有某个注解
        ComponentScan componentScanAnnotation = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);

        if(componentScanAnnotation != null){
            for (String packageName : componentScanAnnotation.basePackages()) {
                log.info("packageName => {}",packageName);
                //需要将包名转换为类路径
                //com.zdjx.springdemo.component => classpath*:com/zdjx/springdemo/component*.class
                String classPath = "classpath*:" + packageName.replace(".","/") + "*.class";
                log.info("将包名转化为类路径后 => {}",classPath);
                //根据类路径获取资源
                Resource[] resources = context.getResources(classPath);
                for (Resource resource : resources) {
                    log.info("resource => {}",resources);
                }
            }
        }

TestMain.java

@Slf4j
public class TestMain {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config", Config.class);

        
        //AnnotationUtils => Spring提供的工具类 , 查找某个类上是否有某个注解
        ComponentScan componentScanAnnotation = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);

        if(componentScanAnnotation != null){
            for (String packageName : componentScanAnnotation.basePackages()) {
                log.info("packageName => {}",packageName);
                //需要将包名转换为类路径
                //com.zdjx.springdemo.component => classpath*:com/zdjx/springdemo/component*.class
                String classPath = "classpath*:" + packageName.replace(".","/") + "*.class";
                log.info("将包名转化为类路径后 => {}",classPath);
                //根据类路径获取资源
                Resource[] resources = context.getResources(classPath);
                for (Resource resource : resources) {
                    log.info("resource => {}",resources);
                }
            }
        }

        //初始化容器
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        //销毁容器
        context.close();
    }
}

运行

到目前为止 获取到了 类路径下的资源 , 接下来判断这些类上是否加了 @Component 注解 , 来进行模拟@ComponentScan生效

020-2 模拟@ComponentScan注解具有扫描@Component注解的能力
if(componentScanAnnotation != null){
            for (String packageName : componentScanAnnotation.basePackages()) {
                log.info("packageName => {}",packageName);
                //需要将包名转换为类路径
                //com.zdjx.springdemo.component => classpath*:com/zdjx/springdemo/component*.class
                String classPath = "classpath*:" + packageName.replace(".","/") + "*.class";
                log.info("将包名转化为类路径后 => {}",classPath);
                //Spring工具类读取类的元信息
                CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
                //根据类路径获取资源
                Resource[] resources = context.getResources(classPath);
                for (Resource resource : resources) {
                    MetadataReader reader = factory.getMetadataReader(resource);
                    log.info("类名 => {}",reader.getAnnotationMetadata().getClassName());
                    log.info("类是否加了@Component => {}",reader.getAnnotationMetadata().hasAnnotation(Component.class.getName()));
                    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                }
            }
        }

TestMain.java

@Slf4j
public class TestMain {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config", Config.class);

        
        //AnnotationUtils => Spring提供的工具类 , 查找某个类上是否有某个注解
        ComponentScan componentScanAnnotation = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);

        if(componentScanAnnotation != null){
            for (String packageName : componentScanAnnotation.basePackages()) {
                log.info("packageName => {}",packageName);
                //需要将包名转换为类路径
                //com.zdjx.springdemo.component => classpath*:com/zdjx/springdemo/component*.class
                String classPath = "classpath*:" + packageName.replace(".","/") + "*.class";
                log.info("将包名转化为类路径后 => {}",classPath);
                //Spring工具类读取类的元信息
                CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
                //根据类路径获取资源
                Resource[] resources = context.getResources(classPath);
                for (Resource resource : resources) {
                    MetadataReader reader = factory.getMetadataReader(resource);
                    log.info("类名 => {}",reader.getAnnotationMetadata().getClassName());
                    log.info("类是否加了@Component => {}",reader.getAnnotationMetadata().hasAnnotation(Component.class.getName()));
                    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                }
            }
        }

        //初始化容器
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        //销毁容器
        context.close();
    }
}

运行

Bean4上没有添加@Component注解

020-3 添加扫描@Component派生注解的能力

添加扫描@Component派生注解的能力 , 比如@Controller @Service ....

Bean4.java

将Bean4 添加 @Controller 注解

@Slf4j
@Controller
public class Bean4 {
    public Bean4() {
        log.info("我被 Spring 管理了 ");
    }
}
log.info("类是否加了@Component派生注解 => {}",reader.getAnnotationMetadata().hasMetaAnnotation(Component.class.getName()));

TestMain.java

@Slf4j
public class TestMain {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config", Config.class);

        
        //AnnotationUtils => Spring提供的工具类 , 查找某个类上是否有某个注解
        ComponentScan componentScanAnnotation = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);

        if(componentScanAnnotation != null){
            for (String packageName : componentScanAnnotation.basePackages()) {
                log.info("packageName => {}",packageName);
                //需要将包名转换为类路径
                //com.zdjx.springdemo.component => classpath*:com/zdjx/springdemo/component*.class
                String classPath = "classpath*:" + packageName.replace(".","/") + "*.class";
                log.info("将包名转化为类路径后 => {}",classPath);
                //Spring工具类读取类的元信息
                CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
                //根据类路径获取资源
                Resource[] resources = context.getResources(classPath);
                for (Resource resource : resources) {
                    MetadataReader reader = factory.getMetadataReader(resource);
                    log.info("类名 => {}",reader.getAnnotationMetadata().getClassName());
                    log.info("类是否加了@Component => {}",reader.getAnnotationMetadata().hasAnnotation(Component.class.getName()));
                    log.info("类是否加了@Component派生注解 => {}",reader.getAnnotationMetadata().hasMetaAnnotation(Component.class.getName()));
                    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                }
            }
        }

        //初始化容器
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        //销毁容器
        context.close();
    }
}

运行

021-第五讲-工厂后处理器模拟实现-组件扫描

根据获取到的类的元信息 , 生成beanDefinition , 进行Bean的注册

  • 判断是否加了 @Component 以及其派生注解
  • 根据获取到的类的元信息 , 生成beanDefinition , 进行Bean的注册
  • 生产Bean的名字
  • 注册
if(reader.getAnnotationMetadata().hasAnnotation(Component.class.getName()) ||   //是否加了@Component注解
                            reader.getAnnotationMetadata().hasAnnotation(Component.class.getName()) //是否加了@Component派生注解
                    ){
                        //创建BeanDefinitionBuilder
                        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
                                .genericBeanDefinition(reader.getClassMetadata().getClassName())
                                .getBeanDefinition();

                        //产生Bean的名字
                        DefaultListableBeanFactory defaultListableBeanFactory = context.getDefaultListableBeanFactory();
                        String generatedBeanName = generator.generateBeanName(beanDefinition, defaultListableBeanFactory);
                        //根据 beanDefinitionName 注册 Bean
                        defaultListableBeanFactory.registerBeanDefinition(generatedBeanName,beanDefinition);//参数还需要一个bean的名字
                    }

TestMain.java

@Slf4j
public class TestMain {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config", Config.class);
        
        //AnnotationUtils => Spring提供的工具类 , 查找某个类上是否有某个注解
        ComponentScan componentScanAnnotation = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);
        if(componentScanAnnotation != null){
            for (String packageName : componentScanAnnotation.basePackages()) {
                log.info("packageName => {}",packageName);
                //需要将包名转换为类路径
                //com.zdjx.springdemo.component => classpath*:com/zdjx/springdemo/component*.class
                String classPath = "classpath*:" + packageName.replace(".","/") + "*.class";
                log.info("将包名转化为类路径后 => {}",classPath);
                //Spring工具类读取类的元信息
                CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
                //根据类路径获取资源
                Resource[] resources = context.getResources(classPath);
                //产生Bean的名字
                AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();
                for (Resource resource : resources) {
                    MetadataReader reader = factory.getMetadataReader(resource);
                    log.info("类名 => {}",reader.getAnnotationMetadata().getClassName());
                    log.info("类是否加了@Component => {}",reader.getAnnotationMetadata().hasAnnotation(Component.class.getName()));
                    log.info("类是否加了@Component派生注解 => {}",reader.getAnnotationMetadata().hasMetaAnnotation(Component.class.getName()));
                    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

                    if(reader.getAnnotationMetadata().hasAnnotation(Component.class.getName()) ||   //是否加了@Component注解
                            reader.getAnnotationMetadata().hasAnnotation(Component.class.getName()) //是否加了@Component派生注解
                    ){
                        //创建BeanDefinitionBuilder
                        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
                                .genericBeanDefinition(reader.getClassMetadata().getClassName())
                                .getBeanDefinition();

                        //产生Bean的名字
                        DefaultListableBeanFactory defaultListableBeanFactory = context.getDefaultListableBeanFactory();
                        String generatedBeanName = generator.generateBeanName(beanDefinition, defaultListableBeanFactory);
                        //根据 beanDefinitionName 注册 Bean
                        defaultListableBeanFactory.registerBeanDefinition(generatedBeanName,beanDefinition);//参数还需要一个bean的名字
                    }
                }
            }
        }

        //初始化容器
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        //销毁容器
        context.close();
    }
}

021-2 抽取为BeanFactoryPostProcessor

将上面的主方法中扫描@Component的逻辑抽取出来

@Slf4j
public class TestMain {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config", Config.class);

        

        //初始化容器
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        //销毁容器
        context.close();
    }
}

抽取 ==> ComponentScanPostProcessor.class

@Slf4j
public class ComponentScanPostProcessor implements BeanFactoryPostProcessor {
    @Override //context.refresh
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        try {
            
            //AnnotationUtils => Spring提供的工具类 , 查找某个类上是否有某个注解
            ComponentScan componentScanAnnotation = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);
            if(componentScanAnnotation != null){
                for (String packageName : componentScanAnnotation.basePackages()) {
                    log.info("packageName => {}",packageName);
                    //需要将包名转换为类路径
                    //com.zdjx.springdemo.component => classpath*:com/zdjx/springdemo/component*.class
                    String classPath = "classpath*:" + packageName.replace(".","/") + "*.class";
                    log.info("将包名转化为类路径后 => {}",classPath);
                    //Spring工具类读取类的元信息
                    CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
                    //根据类路径获取资源
                    Resource[] resources = new PathMatchingResourcePatternResolver().getResources(classPath);
                    //产生Bean的名字
                    AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();
                    for (Resource resource : resources) {
                        MetadataReader reader = factory.getMetadataReader(resource);
                        //log.info("类名 => {}",reader.getAnnotationMetadata().getClassName());
                        //log.info("类是否加了@Component => {}",reader.getAnnotationMetadata().hasAnnotation(Component.class.getName()));
                        //log.info("类是否加了@Component派生注解 => {}",reader.getAnnotationMetadata().hasMetaAnnotation(Component.class.getName()));
                        //log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

                        if(reader.getAnnotationMetadata().hasAnnotation(Component.class.getName()) ||   //是否加了@Component注解
                                reader.getAnnotationMetadata().hasMetaAnnotation(Component.class.getName()) //是否加了@Component派生注解
                        ){
                            //创建BeanDefinitionBuilder
                            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
                                    .genericBeanDefinition(reader.getClassMetadata().getClassName())
                                    .getBeanDefinition();

                            if(configurableListableBeanFactory instanceof DefaultListableBeanFactory ){
                                DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableListableBeanFactory;
                                //产生Bean的名字
                                String generatedBeanName = generator.generateBeanName(beanDefinition, defaultListableBeanFactory);
                                log.info("generatedBeanName => {}",generatedBeanName);
                                //根据 beanDefinitionName 注册 Bean
                                defaultListableBeanFactory.registerBeanDefinition(generatedBeanName,beanDefinition);//参数还需要一个bean的名字
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

调用 => ComponentScanPostProcessor.class 的 MainTest.java

@Slf4j
public class TestMain {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config", Config.class);

        
        context.registerBean(ComponentScanPostProcessor.class);

        //初始化容器
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        //销毁容器
        context.close();
    }
}

022-第五讲-工厂后处理器模拟实现-@Bean 022-1 - 模拟@Bean

Bean1.class

@Slf4j
public class Bean1 {}

Config.class

@ComponentScan("com.zdjx.springdemo.component")
public class Config {

    public Bean2 bean2(){
        return new Bean2();
    }

    @Bean
    public Bean1 bean1(){
        return new Bean1();
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){ //工厂方法的参数
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean(initMethod = "init")
    public DruidDataSource dataSource() throws SQLException, SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setDriver(new com.mysql.jdbc.Driver());
        return dataSource;
    }
}

TestMain.java

@Slf4j
public class TestComponentScan {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config",Config.class);

      

        CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
        MetadataReader reader = factory.getMetadataReader(new ClassPathResource("com/zdjx/springdemo/config/Config.class"));
        Set methods = reader.getAnnotationMetadata().getAnnotatedMethods(Bean.class.getName());
        for (MethodMetadata method : methods) {
            log.info("method => {}",method.getMethodName());

            
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
            //Config类作为工厂 , 方法作为产品
            builder.setFactoryMethodOnBean(method.getMethodName(),"config");
            AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
            context.registerBeanDefinition(method.getMethodName(),beanDefinition);

        }

        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

    }
}

运行

 缺少工厂方法的装配模式

022 - 2 - 设置工厂方法的装配模式
//设置自动装配模式 => 否则 sqlSessionBean 无法加入到容器中 , 对于构造方法的参数 , 还有对于工厂方法的参数
//如果想自动装配 , 选择的装配模式未 AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR
builder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);

TestMain.java

@Slf4j
public class TestComponentScan {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config",Config.class);

        ComponentScan componentScanAnnotation
                = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);

        CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
        MetadataReader reader = factory.getMetadataReader(new ClassPathResource("com/zdjx/springdemo/config/Config.class"));
        Set methods = reader.getAnnotationMetadata().getAnnotatedMethods(Bean.class.getName());
        for (MethodMetadata method : methods) {
            log.info("method => {}",method.getMethodName());

            
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
            //Config类作为工厂 , 方法作为产品
            builder.setFactoryMethodOnBean(method.getMethodName(),"config");
            //设置自动装配模式 => 否则 sqlSessionBean 无法加入到容器中 , 对于构造方法的参数 , 还有对于工厂方法的参数
            //如果想自动装配 , 选择的装配模式未 AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR
            builder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
            AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
            context.registerBeanDefinition(method.getMethodName(),beanDefinition);

        }

        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }
    }
}

运行

022 - 3 - 演示@Bean注解的解析过程
            String initMethodStr = method.getAnnotationAttributes(Bean.class.getName()).get("initMethod").toString();


//......

if(initMethodStr.length()>0)
    {
          builder.setInitMethodName(initMethodStr);
    }

TestMain.java

@Slf4j
public class TestComponentScan {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config",Config.class);

        ComponentScan componentScanAnnotation
                = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);

        CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
        MetadataReader reader = factory.getMetadataReader(new ClassPathResource("com/zdjx/springdemo/config/Config.class"));
        Set methods = reader.getAnnotationMetadata().getAnnotatedMethods(Bean.class.getName());
        for (MethodMetadata method : methods) {
            log.info("method => {}",method.getMethodName());

            
            String initMethodStr = method.getAnnotationAttributes(Bean.class.getName()).get("initMethod").toString();

            
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
            //Config类作为工厂 , 方法作为产品
            builder.setFactoryMethodOnBean(method.getMethodName(),"config");

            if(initMethodStr.length()>0){
                builder.setInitMethodName(initMethodStr);
            }


            //设置自动装配模式 => 否则 sqlSessionBean 无法加入到容器中 , 对于构造方法的参数 , 还有对于工厂方法的参数
            //如果想自动装配 , 选择的装配模式未 AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR
            builder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
            AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
            context.registerBeanDefinition(method.getMethodName(),beanDefinition);

        }

        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }
    }
}
022- 4 抽取@Bean的后处理器

抽取 => AtBeanPostProcessor.java

@Slf4j
public class AtBeanPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        try {
            CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
            MetadataReader reader = factory.getMetadataReader(new ClassPathResource("com/zdjx/springdemo/config/Config.class"));
            Set methods = reader.getAnnotationMetadata().getAnnotatedMethods(Bean.class.getName());
            for (MethodMetadata method : methods) {
                log.info("method => {}",method.getMethodName());

                
                String initMethodStr = method.getAnnotationAttributes(Bean.class.getName()).get("initMethod").toString();

                
                BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
                //Config类作为工厂 , 方法作为产品
                builder.setFactoryMethodOnBean(method.getMethodName(),"config");

                if(initMethodStr.length()>0){
                    builder.setInitMethodName(initMethodStr);
                }


                //设置自动装配模式 => 否则 sqlSessionBean 无法加入到容器中 , 对于构造方法的参数 , 还有对于工厂方法的参数
                //如果想自动装配 , 选择的装配模式未 AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR
                builder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
                AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
                if(configurableListableBeanFactory instanceof DefaultListableBeanFactory){
                    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) configurableListableBeanFactory;
                    beanFactory.registerBeanDefinition(method.getMethodName(),beanDefinition);
                }

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

    }
}

调用 => MainTest.java

@Slf4j
public class TestComponentScan {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config",Config.class);

        context.registerBean(AtBeanPostProcessor.class);
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }
    }
}

023 - 第五讲 - 工厂后处理器模拟实-@Mapper-逐个添加

其实Spring并不能管理一个接口 , 最终还是管理的一个个对象.

Mapper1.interface

@Mapper
public interface Mapper1 {
}

Mapper2.interface

@Mapper
public interface Mapper2 {
}

Config.class

@Bean
    public MapperFactoryBean mapper1(SqlSessionFactory sqlSessionFactory){
        MapperFactoryBean factory = new MapperFactoryBean<>(Mapper1.class);
        factory.setSqlSessionFactory(sqlSessionFactory);
        return factory;
    }

    @Bean
    public MapperFactoryBean mapper2(SqlSessionFactory sqlSessionFactory){
        MapperFactoryBean factory = new MapperFactoryBean<>(Mapper2.class);
        factory.setSqlSessionFactory(sqlSessionFactory);
        return factory;
    }

@Configuration
@ComponentScan("com.zdjx.springdemo.component")
public class Config {

    public Bean2 bean2(){
        return new Bean2();
    }

    @Bean
    public Bean1 bean1(){
        return new Bean1();
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){ //工厂方法的参数
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean(initMethod = "init")
    public DruidDataSource dataSource() throws SQLException, SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setDriver(new com.mysql.jdbc.Driver());
        return dataSource;
    }

    @Bean
    public MapperFactoryBean mapper1(SqlSessionFactory sqlSessionFactory){
        MapperFactoryBean factory = new MapperFactoryBean<>(Mapper1.class);
        factory.setSqlSessionFactory(sqlSessionFactory);
        return factory;
    }

    @Bean
    public MapperFactoryBean mapper2(SqlSessionFactory sqlSessionFactory){
        MapperFactoryBean factory = new MapperFactoryBean<>(Mapper2.class);
        factory.setSqlSessionFactory(sqlSessionFactory);
        return factory;
    }


}

TestMain.java

@Slf4j
public class TestComponentScan {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config",Config.class);
        context.registerBean(AtBeanPostProcessor.class);
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        context.close();
    }
}

024 - 第五讲 - 工厂后处理器模拟实-@Mapper-扫描批量添加

Config.class

@ComponentScan("com.zdjx.springdemo.component")
public class Config {

    public Bean2 bean2(){
        return new Bean2();
    }

    @Bean
    public Bean1 bean1(){
        return new Bean1();
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){ //工厂方法的参数
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean(initMethod = "init")
    public DruidDataSource dataSource() throws SQLException, SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setDriver(new com.mysql.jdbc.Driver());
        return dataSource;
    }

}

MapperPostProcessor.java

public class MapperPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @SneakyThrows
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanFactory) throws BeansException {
        PathMatchingResourcePatternResolver resolver =
                new PathMatchingResourcePatternResolver();

        Resource[] resources = resolver.getResources("classpath*:com/zdjx/springdemo/mapper*.class");
        AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();
        CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
        for (Resource resource : resources) {
            MetadataReader reader = factory.getMetadataReader(resource);
            ClassMetadata classMetadata = reader.getClassMetadata();
            //如果是 接口 => Mapper1:true  Mapper2:true  Mapper3:true
            if(classMetadata.isInterface()){
                AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(MapperFactoryBean.class)
                        .addConstructorArgValue(classMetadata.getClassName())
                        .setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE)
                        .getBeanDefinition();
                //根据Mapper接口生成了beanDefinition
                AbstractBeanDefinition beanDefinition2 = BeanDefinitionBuilder.genericBeanDefinition(classMetadata.getClassName()).getBeanDefinition();
                //根据mapper的名字 重新生成bean的名字
                String name = generator.generateBeanName(beanDefinition2,beanFactory);
                beanFactory.registerBeanDefinition(name,beanDefinition);

            }
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}

TestMain.java

@Slf4j
public class TestComponentScan {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config",Config.class);
        context.registerBean(AtBeanPostProcessor.class);
        context.registerBean(MapperPostProcessor.class);
        context.refresh();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            log.info("beanDefinitionName => {}",beanDefinitionName);
        }

        context.close();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/981543.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号