Spring源码学习BeanDefinitionRegistryPostProcessor

一、概述

  因继承了BeanFactoryPostProcessor后置处理器(https://www.cnblogs.com/kjcc/p/13571951.html),可以在bean实例化之前对bean定义进行修改

  

 postProcessBeanDefinitionRegistry()方法作用将bean的定义注册到容器中
 
 执行顺序:PostProcessorRegistrationDelegate代理类中先执行postProcessBeanDefinitionRegistry()方法,在执行BeanFactoryPostProcessor后置处理器中的方法
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

    void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}

  

 

二、demo演示

  1、创建实体类(主要对User的定义进行操作)

    

@Data
public
class User { String name; }

  2、BeanDefinitionRegistryPostProcessor接口实现类

    

@Component
public class TestBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor{

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
         String[]  names=beanFactory.getBeanDefinitionNames();
            for(String name:names) {
                if("test".equals(name)) {
                    BeanDefinition  beanDefinition=beanFactory.getBeanDefinition(name);
                    MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
                        propertyValues.addPropertyValue("name", "Jack");
                        System.out.println("修改了name");
                    
                }
            }

    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // TODO Auto-generated method stub
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(User.class);
        System.out.println("注册bean 的定义");
        registry.registerBeanDefinition("test", rootBeanDefinition);
    }

}

 3、运行测试,springboot启动时候刷新上下文会通过PostProcessorRegistrationDelegate代理类调用该类

   

    

posted @ 2020-10-28 15:03  StrangerIt  阅读(243)  评论(0)    收藏  举报