把自己知道的小知识点全部记录,😄

BeanDefinitionRegistryPostProcessor 接口属于Beanddefination  装配定义的范畴,此时bean 并没有初始化

 BeanPostProcessor属于be an 实例化修改的范畴,be an 已经进行实例化,只不过我们可以修改这个be an 的实例化两个接口所对应的对象不一样

研究过Mybatis 源码的童鞋, org.mybatis.spring.mapper.MapperScannerConfigurer 扫描接口的这个类实现了BeanDefinitionRegistryPostProcessor 这个接口

 

BeanDefinitionRegistryPostProcessor :是Spring提供的BeanDefinaion 后置工厂处理器,可以进行Beandefination 的添加修改删除的操作;接下来我们看一下

 1. 如何进行Beandefination 的添加,修改,删除操作

 2.  Spring 哪里进行BeanDefinitionRegistryPostProcessor 后置处理器的调用

 

添加Beandefination 操作:

@Service
public class BeanPostDefination implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        int before = registry.getBeanDefinitionCount();
        System.out.println("后置处理之前的bean个数"+before);
        //bean的定义
        GenericBeanDefinition beanDefinition =new GenericBeanDefinition();
        //设置bean class对象交给BeanFactory 进行创建
        beanDefinition.setBeanClass(UserModel.class);
        //也可以给置顶bean 进行属性的添加,底层是一个arraylist
        beanDefinition.getPropertyValues().addPropertyValue("name", "cys");
        //注册到bean工厂中将bean
        registry.registerBeanDefinition("userModel", beanDefinition);
        System.out.println("后置处理之后的bean个数"+registry.getBeanDefinitionCount());


    }

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

测试:

 public static void main(String[] args) throws Exception {
        ClassPathXmlApplicationContext context =new ClassPathXmlApplicationContext("classpath:spring/whoareyou.xml");
        UserModel userModel = (UserModel)context.getBean("userModel");
        System.out.println(userModel.getName());
    }

打印结果: be an的个数增加,并且能够得到我们添加的属性

删除操作:

 //删除操作根据名字
  registry.removeBeanDefinition("xxx");

 

OK,那么,这个处理器在何时被调用呢?追踪源码:有基础的童鞋应该很熟悉这个refresh()这个方法吧 

点进去,里面没有复杂的逻辑,进行判断然后实例化,调用

这样Spring 的冰山一角就就完事了,

 

我们再看一下 BeanPostProcessor 这个后置处理器, BeanPostProcessor处理器的作用在be an 初始化实例化的范畴,可以进行be an 实例修改,比如AOP 生成cglib动态代理

而 BeanDefinitionRegistryPostProcessor 接口属于Beanddefination  装配定义的范畴

我们看一下调用他们的方法: 

我们看一下,在哪里进行调用的:

源码很明白 了,根本用不上我们测试,哪个执行在前面哪个执行在后面:

就是 Bean 实例化-->AutoWrized 属性的注入--> 执行Aware 接口的方法-->执行BeanPostProcessor 的前置方法 postProcessBeforeInitialization -->

执行 InitalizingBean 的 afterPropertiesSet 方法 -->执行BeanPostProcessor 的后置方法 postProcessAfterInitialization

 

posted on 2019-03-09 20:20  iscys  阅读(767)  评论(0编辑  收藏  举报