spring IOC源码分析(一)bean工厂的创建加载过程

最近学的比较散乱,没有真正学到比较重要的东西。这几天把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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值