spring(八)-------invokeBeanFactoryPostProcessors中getBeanFactoryPostProcessors()方法

	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		//注意:getBeanFactoryPostProcessors()是获取自定义的(什么是自定义?就是我们自己写的,而且还没有交给spring管理,即还没有加上@Component)
		//测试方法。在refresh之前使用addBeanFactoryPostProcessor方法来达到自定义 。
		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

		// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
		// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
		if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}
	}

为什么要把这个方法单独拿出来说呢?因为这个方法跟普通的理解并不一样。上面的注释可能没有说服力。下面就用实际操作解释一下。
首先,我们建立几个文件并加上@Component。像这样:

package com.test.com.test.App;

import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

@Component
@Import(X.class)
public class Ctest {
}

可以自己多加类似的文件,要让@ComponentScan扫描到这个类,然后断点调试。调试后结果如下:
加了@Component执行之后的由图片可以知道此时beanFactoryPostProcessors的size为0,说明加@Component并没有用。下面就试试使用addBeanFactoryPostProcessor方法。
首先编写一个类,不交给spring管理,即不加@Component。如下:

package com.test.mytest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class MYgetBeanFactoryPostProcessors implements BeanFactoryPostProcessor {
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

	}
}

主函数上这样写:

package com.test;

import com.test.com.test.App.Appconfig;
import com.test.mytest.MYgetBeanFactoryPostProcessors;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Test {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext();
		ac.register(Appconfig.class);
		ac.addBeanFactoryPostProcessor(new MYgetBeanFactoryPostProcessors());
		ac.refresh();
	}
}

再次断点执行,结果如下:
在这里插入图片描述可以看见MYgetBeanFactoryPostProcessors已经被添加到beanFactoryPostProcessors中了,为什么要专门说这个呢,主要是为了更方便的看源码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值