Spring容器 —— 深入 bean 的加载(五、初始化 bean)

上篇分析了 bean 中属性注入的方式,在注入了属性之后,就需要初始化 bean 了,这部分工作完成了 bean 配置中 init-methos 属性指定方法的内容,由 initializeBean 函数完成。

初始化流程

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			// 对特殊的 bean 处理:Aware、BeanClassLoaderAware、BeanFactory
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			// 初始化前后处理器应用
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			// 调用用户配置的 init-method
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			// 初始化后后处理器应用
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

该函数的主要功能就是对用户自定义的 init-method 函数进行调用。

激活 Aware 方法

Aware 相关的接口的主要作用是向对应的实现中注入被 Aware 的类型,如 BeanFactoryAware 就会注入 BeanFactory,同理 ApplicationContextAware 会注入 ApplicationContext。

激活自定义 init 方法

用户定义初始化方法除了配置 init-method 之外,还可以自定义 bean 实现 InitializingBean 接口,并在 afterPropertiesSet 中实现自己的初始化业务逻辑。init-method 和 afterPropertiesSet 都是在初始化 bean 的时候执行的,先 afterPropertiesSet 后 init-method。

上一篇:Spring IOC学习(5)——AbstractAutowireCapableBeanFactory


下一篇:Spring IOC 启动过程?