入口处
((AbstractApplicationContext) applicationContext).refresh();
可以看见这里是执行了 AbstractApplicationContext 的refresh 方法。
本文的 wen环境 ,因此是 ServletWebServerApplicationContext,话不多少,最终执行的还是 父类AbstractApplicationContext的方法
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//告诉子类刷新内部bean工厂
//这里没有很明白刷新的意义
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//准备bean工厂,以便在此上下文中使用。
/*这里其他乱七八糟的都没看,但是看见了熟悉的
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
那大致意思就理解了,给容器一个东西,比如说这里添加的bean的处理器
*/
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//允许在上下文子类中对bean工厂进行后处理。
/*
简单看了下,这里是给不同的环境的上下文提供了添加一些后置处理器的口子,
这里说的允许 其实就是添加一些后置处理器进去
既然这里是允许不同容器给自己添加的后置,那自定义的后置处理器是在哪里加入容器的???,难道是通过包扫描进去的?
*/
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//调用上下文中注册为bean的工厂处理器。
/**
BeanFactoryPostProcessors
这里
1.将 @Configuration类添加容器
2.将 @Configuration 的内部配置的@bean加载进容器
注意这里并没有实例化
疑问:
BeanFactoryPostProcessors 是什么时候加到容器里边的
答:发现 是BeanFactoryPostProcessors这个,那么调试这个类注加入入进容器的时机就可以了
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
调试发现,这货实在创建上下文的时候,就注册进去了。
而且,还发现 以internal 开头的处理器,都是Spring在启动的时候,自己初始化进去的,而且注册的名字还是被改变了
的,比如 org.springframework.context.annotation.internalConfigurationAnnotationProcessor
的实际的类名是ConfigurationClassPostProcessor
*/
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注册拦截bean创建的bean处理器。
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//初始化此上下文的消息源。
initMessageSource();
// Initialize event multicaster for this context.
//初始化此上下文的事件多播程序。
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//在特定上下文子类中初始化其他特殊bean
onRefresh();
// Check for listener beans and register them.
//检查侦听器bean并注册它们。
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//实例化所有剩余的(非惰性初始化)单例。
/*
*这里实例化的所有的单例的bean 实际上就是在 invokeBeanFactoryPostProcessors 通过
ConfigurationClassPostProcessor 中包扫描 加载进容器的bean
*/
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
理清楚了:
我们通过注解加载进容器中的bean,实际上实在 invokeBeanFactoryPostProcessors 的过程中,通过ConfigurationClassPostProcessor的扫描注册上去,而ConfigurationClassPostProcessor是springBoot在启动中,创建容器的时候就,加载了这个后置处理器,完成包扫描加载任务,之后在finishBeanFactoryInitialization中完成对 所有注册的bean的实例化。
下一次理清楚:
1.BeanFactoryPostProcessors 跟BeanPostProcessors 的区别
2.理清楚自动注入的实现实现过程。
3.以及理解Spring中的钩子函数的种类