DefaultListableBeanFactory 对象自定义赋值

今天我们分享自定义修改源码:首先看看一处源码是怎样执行的

try {
      //创建DefaultListableBeanFactory
      //BeanFactory 实例工厂
      DefaultListableBeanFactory beanFactory = createBeanFactory();
      beanFactory.setSerializationId(getId());
 
      //设置是否可以循环依赖 allowCircularReferences
      //是否允许使用相同名称重新注册不同的bean实现.
      //此处默认都是null,业务代码可以自定义实现,类似于修改源码,这里我们会单独分析
      customizeBeanFactory(beanFactory);
 
      //解析xml,并把xml中的标签封装成BeanDefinition对象
      loadBeanDefinitions(beanFactory);
      synchronized (this.beanFactoryMonitor) {
         this.beanFactory = beanFactory;//赋值给成员变量,对应上面的 return getBeanFactory(); 代码
      }

 

处理:  customizeBeanFactory(beanFactory);点击进入

	protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
		if (this.allowBeanDefinitionOverriding != null) {
			beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
		}
		if (this.allowCircularReferences != null) {
			beanFactory.setAllowCircularReferences(this.allowCircularReferences);
		}
	}

初始化默认为空:

@Nullable
	private Boolean allowBeanDefinitionOverriding;

	@Nullable
	private Boolean allowCircularReferences;

2、从源码里看,他们都有赋值的地方:即其他业务流程赋值

public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) {
		this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding;
	}

3、业务代码自定义处理:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

 
@Component //该注解一定要加
public class BeanPro implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {

    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        DefaultListableBeanFactory beanFactory1 = (DefaultListableBeanFactory)beanFactory;
        beanFactory1.setAllowBeanDefinitionOverriding(true);//设置可覆盖
        beanFactory1.setAllowCircularReferences(true);//设置可以循环依赖
    }
}

到此,我们分享了一个源码修改的例子,大家可以举一反三,多多尝试,定会收获很多。

你可能感兴趣的:(spring源码学习,spring,boot,spring)