BeanFactoryPostProcessor:beanFactory的后置处理器,在BeanFactory标准初始化之后调用,来定制和修改BeanFactory的内容,此时所有的bean定义已经保存并加载到beanFactory,但是bean的实例还未创建,beanFactory实际上就是spring的容器
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);//实例化bean
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanFactoryPostProcessor ... postProcessBeanFactory ...");
int count = beanFactory.getBeanDefinitionCount();
String[] names = beanFactory.getBeanDefinitionNames();
System.out.println("定义了:" + count + "个bean,名字是:" + Arrays.asList(names));
}
}
BeanPostProcessor也是后置处理期,但BeanPostProcessor的调用时机是在bean创建之后,执行bean的初始化方法的前后调用其前置方法和后置方法。
Java1.8之后interface的方法在定义时也可以有方法体了,有方法体的接口方法必须使用default修饰,类似于父类:
public interface NullablIenterface {
// @Nullable
default void sayHello(String name) {
System.out.println("hello" + name);
}
public void sayBye();
}
BeanFactoryPostProcessor的原理:
1)、ioc容器创建对象前:refresh()
2)、invokeBeanFactoryPostProcessors(beanFactory);
如何找到所有的BeanFactoryPostProcessor并执行他们的方法
1)、直接在BeanFactory中找到所有类型是BeanFactoryPostProcessor的组件,并执行它们的postProcessBeanFactory方法:要求实现BeanFactoryPostProcessor接口,并且被纳入到IOC容器管理
2)、在初始化创建其他组件前面执行:finishBeanFactoryInitialization(beanFactory);//初始化组件