最近学的比较散乱,没有真正学到比较重要的东西。这几天把sprign源码再看一遍,整理下以前看的经历,同时把相关的个人心得记录下来。
spring两大功能模块,IOC和AOP,在之前已经知到了IOC原理是反射来获取bean实例,而AOP是动态代理来实现的。这里先介绍下IOC的源码,它是如何来实现的。当然目前能学到的也只是比较浅的大概流程,再复杂点的看起来就比较吃力了。
推荐在学习spring源码的时候下载一份来,好方便注释。这里先从在一开始学习时见到的说起:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“applicationContext.xml”);
进入ClassPathXmlApplicationContext的构造器,在顺着构造器分析来到这,查看注释:
// 使用给定的父级创建新的ClassPathXmlApplicationContext,
// 从给定的XML文件加载定义。
//加载所有bean定义并创建所有单例
//或者,在进一步配置上下文后手动调用refresh。
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
从代码可以看出这里有两个方法setConfigLocations(configLocations)和重点refresh()。显然前者是进行配置的,打开看到:
public void setConfigLocations(@Nullable String... locations) {
if (locations != null) {
//里面对locations进行了空值判定,如果有一个地址是空的,会抛出异常
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
//进一步解析地址
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
于是spring相关的配置缓存在configLocations中,回到核心方法refresh()中,追踪打开:
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.
//配置bean工厂以便在此上下文中使用。
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//允许在上下文的子类中对bean factory进行后处理
//注册request/session scopes,一个ServletContextAwareProcessor处理器等。
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//在上下文中调用注册为bean的工厂处理器。
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that inte