springboot源码学习笔记系列一
笔者大学刚毕业满半年,虽然找到一份程序猿的工作,但了解到这个行业学习是永无止境,因此开始学习和解读springboot的源码,并写下该系列日记,以激励和警醒自己并分享自己的学习内容。如有错误,欢迎各位大佬的批评指正。
bean的注入装配
spring的核心可以分为IOC和AOP,IOC即为控制反转,通过spring的IOC容器来创建对象,而不是通过程序员来创建。那么spring是怎么来帮你创建对象的呢?这部分我是通过网上的视频课程进行学习的。刚上手可能都不知道从那里看起,于是,我便通过网上的一些视频进行了了解。这些对象我们一般把它叫做bean,bean在springboot中的注入一般可以通过xml和注解注入的方式进行,@AutoWired和的形式我们都比较熟悉。无论是哪种方法,spring都会通过读取文件转换为BeanDefinition,而从bean的文件到BeanDefinition是通过BeanDefinitionReader来实现的,随后BeanDefinition通过BeanFactoryPostProcessor,即bean工厂的后置处理器来进行处理,之后便是BeanPostProcessor的后置处理器,这两个PostProcessor程序员都可以自己去实现接口来进行拓展。之后便是通过反射来创建bean。整个流程大概如下图:
bean的流程源码分析
我们先写个方法来注入一个bean
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("syl.xml");
Object stud=context.getBean("student");
System.out.println();
}
随后,写一个对应的xml
<bean class="com.spring.demo.demo.student" name="student">
<property name="username" value="shenyili"/>
<property name="password" value="syl199746"/>
</bean>
之后通过debug的方式来一点点分析,spring在整个过程干了些什么
1.我们先看到它进入了ClassPathXmlApplicationContext的构造方法
/**
* Create a new ClassPathXmlApplicationContext with the given parent,
* loading the definitions from the given XML files.
* @param configLocations array of resource locations
* @param refresh whether to automatically refresh the context,
* loading all bean definitions and creating all singletons.
* Alternatively, call refresh manually after further configuring the context.
* @param parent the parent context
* @throws BeansException if context creation failed
* @see #refresh()
*/
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
通过查看上面的注释,发现是通过父类ApplicationContext 创建一个ClassPathXmlApplicationContext,载入xml文件读取配置 ,其中调用了setConfigLocations和refresh两个方法,我们传进去的syl.xml便是configLocations的值,注释中写了see #refresh(),那我们进去看看>* _*<。
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// 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);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// 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);
// 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();
contextRefresh.end();
}
}
}
然后,我们就找到了大宝贝,这个便是bean的处理的整个流程。阅读英文注释,我们便可以大概了解每个步骤干了些什么。
prepareRefresh():
准备好context,进去看了下,大概就是对context 一些参数赋初值。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory():
创建bean工厂
prepareBeanFactory(beanFactory):
对创建的bean工厂赋值参数
postProcessBeanFactory(beanFactory):
这部分就是提到的BeanFactory的后置处理器的接口,默认不做任何操作
invokeBeanFactoryPostProcessors(beanFactory):
调用BeanFactoryPostProcessor
registerBeanPostProcessors(beanFactory):
注册BeanPostProcessors并中断bean的创建
beanPostProcess.end():
结束BeanPostProcessors过程
initMessageSource():
这部分好像又是对context的一些信息进行init
initApplicationEventMulticaster():
初始化事务多播器?先记在小本本上,之后再看
onRefresh():
好像是对一些特殊的beans进行init
registerListeners():
检查和注册监听的bean
finishBeanFactoryInitialization(beanFactory):
完成不是懒加载的单例bean
finishRefresh():
发布对应的事件
这些暂时到现在我学的东西,请大家批评指正,之后我应该还会对每个流程进行详细的学习,也会分享自己的学习笔记!