SpringBean生命周期

SpringBean生命周期


前言

Spring提供了一套Bean的创建和管理体系,在谈及bean的生命周期时一般是指单例bean的生命周期,在单例作用域下,Spring有一套完整的单例bean创建体系:getBean() -> doGetBean() -> createBean() -> doCreateBean()
创建流程看起来并不复杂,但是创建流程是一个大型递归,比如一个Servcie中注入了其他bean,那么在创建该service时需要把被注入的bean也创建好,这就存在递归的过程

由于Spring提供了很多扩展和模板方法,可以自定义创建bean的方式,所以流程中的bean可能被提前创建好并返回

了解SpringBean的生命周期,可以方便我们在工作中随意的对bean进行定制,修改和扩展


提示:以下是本篇文章正文内容,下面案例可供参考

一、Spring分解bean的创建步骤

在真正进入创建流程后,有三步核心创建方法,全部走完后视为一个完整bean的诞生

// 匹配合适的构造方法,创建bean对象
// 可能构造方法的入参也是bean,如果是这样需要走创建流程创建该入参(bean)
1. createBeanInstance()

// 针对创建出的bean对象,填充内部属性
2. populateBean(beanName, mbd, instanceWrapper);

// 填充属性后,执行各种初始化逻辑
3. initializeBean(beanName, exposedObject, mbd)

可以看到一个完整的bean分为核心的三个步骤完成,先创建实例,然后填充属性,最后完成初始化方法

二、具体创建步骤

1.万能的refresh

我们认为当一个对象(其实是beanDefinition)加载到容器后,开始创建bean时,一直到结束,视为完整的生命周期

refresh部分代码如下(示例):

	// Instantiate all remaining (non-lazy-init) singletons.
	// 实例化非懒加载的单例bean
	finishBeanFactoryInitialization(beanFactory);

refres方法是必须要了解的Spring核心方法,在实例化bean前有很多核心的准备工作,比如解析xml配置,注入配置类对各种注解进行扫描和解析;实例化并且执行BFPP等,会提前创建好一些内置bean,这些都是创建bean的前置要求

2.创建前的准备工作

进入finishBeanFactoryInitialization方法,代码如下(示例):

	protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		// Initialize conversion service for this context.
		// 设置转换服务
		if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
			beanFactory.setConversionService(
					beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
		}

		// Register a default embedded value resolver if no BeanFactoryPostProcessor
		// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
		// at this point, primarily for resolution in annotation attribute values.
		if (!beanFactory.hasEmbeddedValueResolver()) {
			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
		}

		// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
		for (String weaverAwareName : weaverAwareNames) {
			getBean(weaverAwareName);
		}

		// Stop using the temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(null);

		// Allow for caching all bean definition metadata, not expecting further changes.
		// 开始创建前,先冻结配置
		beanFactory.freezeConfiguration();

		// Instantiate all remaining (non-lazy-init) singletons.
		// 实例化非懒加载的单例
		beanFactory.preInstantiateSingletons();
	}

3.循环创建单例bean

	@Override
	public void preInstantiateSingletons() throws BeansException {
		if (logger.isTraceEnabled()) {
			logger.trace("Pre-instantiating singletons in " + this);
		}

		// Iterate over a copy to allow for init methods which in turn register new bean definitions.
		// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				if (isFactoryBean(beanName)) {
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					if (bean instanceof FactoryBean) {
						FactoryBean<?> factory = (FactoryBean<?>) bean;
						boolean isEagerInit;
						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
							isEagerInit = AccessController.doPrivileged(
									(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
									getAccessControlContext());
						}
						else {
							isEagerInit = (factory instanceof SmartFactoryBean &&
									((SmartFactoryBean<?>) factory).isEagerInit());
						}
						if (isEagerInit) {
							getBean(beanName);
						}
					}
				}
				else {
					getBean(beanName);
				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}

4.真正进入创建逻辑

4.1. getBean()方法是完整创建bean流程的开始,没有任何逻辑
	@Override
	public Object getBean(String name) throws BeansException {
		return doGetBean(name, null, null, false);
	}
4.2. doGetBean(),代码太多,省略了部分
	/**
	 * Return an instance, which may be shared or independent, of the specified bean.
	 * @param name the name of the bean to retrieve
	 * @param requiredType the required type of the bean to retrieve
	 * @param args arguments to use when creating a bean instance using explicit arguments
	 * (only applied when creating a new instance as opposed to retrieving an existing one)
	 * @param typeCheckOnly whether the instance is obtained for a type check,
	 * not for actual use
	 * @return an instance of the bean
	 * @throws BeansException if the bean could not be created
	 */
	@SuppressWarnings("unchecked")
	protected <T> T doGetBean(
			String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
			throws BeansException {

		String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		// 创建前先从缓存中获取bean,如果已经创建好了直接返回,getObjectForBeanInstance是factoryBean处理,一般不会用到
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			// ... 省略日志
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			// ... 省略isPrototypeCurrentlyInCreation校验

			// Check if bean definition exists in this factory.
			BeanFactory parentBeanFactory = getParentBeanFactory();
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// ... 省略父工厂的一些处理
			}

			if (!typeCheckOnly) {
				// 设置一个标志,表示这个bean进入创建逻辑了
				markBeanAsCreated(beanName);
			}

			try {
				// 合并bean定义信息,如果有父类的话
				RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				// Guarantee initialization of beans that the current bean depends on.
				String[] dependsOn = mbd.getDependsOn();
				if (dependsOn != null) {
					// ... 省略 处理depensOn
				}

				// Create bean instance.
				// 如果是单例属性,开始创建
				if (mbd.isSingleton()) {
					// 在getSingleton方法,进入getObject,为createBean逻辑
					sharedInstance = getSingleton(beanName, () -> {
						try {
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							// Explicitly remove instance from singleton cache: It might have been put there
							// eagerly by the creation process, to allow for circular reference resolution.
							// Also remove any beans that received a temporary reference to the bean.
							destroySingleton(beanName);
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				else if (mbd.isPrototype()) {
					// ... 省略原型对象的处理
				}

				else {
					// ... 省略,不是单例也不是原型的处理
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}

		// Check if required type matches the type of the actual bean instance.
		if (requiredType != null && !requiredType.isInstance(bean)) {
				// ... 省略转换服务的处理
			}
		}
		return (T) bean;
	}
4.3. createBean()核心代码
	/**
	 * Central method of this class: creates a bean instance,
	 * populates the bean instance, applies post-processors, etc.
	 * @see #doCreateBean
	 */
	@Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		if (logger.isTraceEnabled()) {
			logger.trace("Creating instance of bean '" + beanName + "'");
		}
		RootBeanDefinition mbdToUse = mbd;

		// Make sure bean class is actually resolved at this point, and
		// clone the bean definition in case of a dynamically resolved Class
		// which cannot be stored in the shared merged bean definition.
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}

		// Prepare method overrides.
		try {
			mbdToUse.prepareMethodOverrides();
		}
		// ... 省略异常处理

		try {
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			// 给BPP一个返回代理对象的机会
			// 这里是一个扩展,可以实现InstantiationAwareBeanPostProcesso#postProcessBeforeInstantiation方法,自己使用代理方法创建对象
			// 可以关注AbstractA
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				// 如果自己创建好了,返回。打断springBean的创建流程
				return bean;
			}
		}
		// ... 省略异常处理

		try {
			// 开始进入核心的创建bean逻辑
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isTraceEnabled()) {
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
		// ... 省略异常处理
	}
4.4 doCreateBean() 核心创建bean逻辑,可以不关心循环依赖和MergeBeanDefinitionBPP的处理
	/**
	 * Actually create the specified bean. Pre-creation processing has already happened
	 * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
	 * <p>Differentiates between default bean instantiation, use of a
	 * factory method, and autowiring a constructor.
	 * @param beanName the name of the bean
	 * @param mbd the merged bean definition for the bean
	 * @param args explicit arguments to use for constructor or factory method invocation
	 * @return a new instance of the bean
	 * @throws BeanCreationException if the bean could not be created
	 * @see #instantiateBean
	 * @see #instantiateUsingFactoryMethod
	 * @see #autowireConstructor
	 */
	protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		// Instantiate the bean.
		// 使用BeanWrapper包装bean,这是Spring特色。封装了一些方法,熟悉后可以去了解
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			// bean生命周期核心方法1:创建实例对象
			// bean必须是public权限的,不然会报错
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		// 获取bean实例
		Object bean = instanceWrapper.getWrappedInstance();
		// bean的class
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					// 这是一个扩展点
					// 执行MergeBeanDefinitionBeanPostProcessor#postProcessMergedBeanDefinition方法
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				// ... 省略异常处理
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		// 允许早期暴露对象,这是解决循环依赖的方式
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			// 往三级缓存中放一个labmda表达式
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
			// bean生命周期核心方法2:填充对象属性
			populateBean(beanName, mbd, instanceWrapper);
			// bean生命周期核心方法2:执行各种初始化方法
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		// ... 省略异常处理

		// 如果是早期暴露的对象,常用于解决循环依赖
		if (earlySingletonExposure) {
			// 从缓存中获取bean
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		// ... 省略异常处理

		return exposedObject;
	}
创建好的bean会放到单例缓存中,方便被获取

三、bean创建详情

了解一下三个创建核心方法的详细步骤

1. 创建对象核心方法一:createBeanInstance

	/**
	 * Create a new instance for the specified bean, using an appropriate instantiation strategy:
	 * factory method, constructor autowiring, or simple instantiation.
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @param args explicit arguments to use for constructor or factory method invocation
	 * @return a BeanWrapper for the new instance
	 * @see #obtainFromSupplier
	 * @see #instantiateUsingFactoryMethod
	 * @see #autowireConstructor
	 * @see #instantiateBean
	 */
	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		// Make sure bean class is actually resolved at this point.
		Class<?> beanClass = resolveBeanClass(mbd, beanName);

		// ... 省略public检验

		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
		 // 可以自己使用supplier的方式创建对象
			return obtainFromSupplier(instanceSupplier, beanName);
		}

		if (mbd.getFactoryMethodName() != null) {
			// 使用factorymethod的方式创建对象
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}

		// Shortcut when re-creating the same bean...
		boolean resolved = false;
		boolean autowireNecessary = false;
		if (args == null) {
			synchronized (mbd.constructorArgumentLock) {
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
		if (resolved) {
			if (autowireNecessary) {
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
				return instantiateBean(beanName, mbd);
			}
		}

		// Candidate constructors for autowiring?
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args);
		}

		// Preferred constructors for default construction?
		ctors = mbd.getPreferredConstructors();
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null);
		}

		// No special handling: simply use no-arg constructor.
		// 使用无参构造方法进行创建
		return instantiateBean(beanName, mbd);
	}
使用无参构造方法进行创建实例
	/**
	 * Instantiate the given bean using its default constructor.
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @return a BeanWrapper for the new instance
	 */
	protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
		try {
			Object beanInstance;
			if (System.getSecurityManager() != null) {
				// ... 省略
			else {
				// 使用构造方法创建实例
				beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
			}
			// 使用BeanWrapper对实例进行包装
			BeanWrapper bw = new BeanWrapperImpl(beanInstance);
			// 初始化包装类,设置转换服务,注册自定义的Editors
			initBeanWrapper(bw);
			return bw;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
		}
	}

2. 创建bean核心方法二:populateBean填充属性

	/**
	 * Populate the bean instance in the given BeanWrapper with the property values
	 * from the bean definition.
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @param bw the BeanWrapper with bean instance
	 */
	@SuppressWarnings("deprecation")  // for postProcessPropertyValues
	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		if (bw == null) {
			// ... 省略处理
		}

		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		// InstancetiationAreaBeanPostProcessor的after方法,这是在实例化之后执行,与前面的createBean中的before方法呼应
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						return;
					}
				}
			}
		}

		// 获取对象属性 解析出的<property/>标签属性
		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
		// 使用byName或byType的方式进行属性注入
		int resolvedAutowireMode = mbd.getResolvedAutowireMode();
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
			// Add property values based on autowire by name if applicable.
			if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}
			// Add property values based on autowire by type if applicable.
			if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}
			pvs = newPvs;
		}

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

		PropertyDescriptor[] filteredPds = null;
		// 如果该bean实现了InstantiationAwareBeanPostProcessor吗,执行postProcessProperties方法
		// 需要关注实现类的metadata.inject方法,该方法解析完后会调用set方法进行属性赋值操作
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						if (filteredPds == null) {
							filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
						}
						pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvsToUse == null) {
							return;
						}
					}
					pvs = pvsToUse;
				}
			}
		}
		if (needsDepCheck) {
			if (filteredPds == null) {
				filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			}
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}

		// 循环解析标签,进行属性填充
		// 关注其内部valueResolver.resolveValueIfNecessary(pv, originalValue)方法,根据传入的标签,解析出标签中设置的值
		// 最终执行到BeanWrapperImpl#setValue方法,获取bean的writeMethod(),其实就是执行set(),设置值
		if (pvs != null) {
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

3. 执行初始化方法initializeBean

	/**
	 * Initialize the given bean instance, applying factory callbacks
	 * as well as init methods and bean post processors.
	 * <p>Called from {@link #createBean} for traditionally defined beans,
	 * and from {@link #initializeBean} for existing bean instances.
	 * @param beanName the bean name in the factory (for debugging purposes)
	 * @param bean the new bean instance we may need to initialize
	 * @param mbd the bean definition that the bean was created with
	 * (can also be {@code null}, if given an existing bean instance)
	 * @return the initialized bean instance (potentially wrapped)
	 * @see BeanNameAware
	 * @see BeanClassLoaderAware
	 * @see BeanFactoryAware
	 * @see #applyBeanPostProcessorsBeforeInitialization
	 * @see #invokeInitMethods
	 * @see #applyBeanPostProcessorsAfterInitialization
	 */
	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 {
			// 执行了三个aware方法,如果该bean是这个三个aware类型
			// 1, beanNameAware.setBeanName()
			// 2, beanClassLoaderAware.setBeanClassLoader()
			// 3, beanFactoryAware.setBeanFactory()
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			// 扩展逻辑,执行BPP的before方法
			// 对已经填充完属性的bean进行BPP的后置处理
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			// 有两个初始化逻辑,两个初始化只能执行一个
			// 1, 执行InitializingBean的afterProperties初始化,这种方式可能用的最多,比如xxljob
			// 2, 执行init-method进行初始化
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		// ...省略异常

		// 执行BPP的after方法,可以关注AbstractAutoProxyCreator wrapIfNecessary方法
		// 如果bean需要被代理,则覆盖成代理对象
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

createBean结束,返回至getSingleton方法,将单例bean添加到一级缓存中(singleObjects),并删除在二级和三级缓存中该bean的缓存
创建结束;
创建结束后会将bean执行registerDisposableBean方法,注册到销毁容器中,方便后期销毁bean,执行destory方法(实现DisposableBean 接口),或配置destory-method

总结

加载xml配置(或doScan进行注解扫描),注册内部类,解析标签,创建BeanDefinition注册到BF容器中
执行并且实例化已经注册的BFPP,注册BPP
进入单例bean创建流程(Spring的单例创建流程):
1,给BeanPostProcessor一个使用代理创建对象的机会, 如果我们选择这种方式,则会结束创建流程,返回代理对象。对应方法resolveBeforeInstantiation()
2,进入doCreateBean逻辑,在createBeanInstance方法中匹配构造方法进行实例化
3,实例化后如果实现了MergedBeanDefinitionPostProcessor,执行该接口的postProcessMergedBeanDefinition方法实现逻辑
4,对实例化的对象进行属性填充:populateBean,这里面会执行InstantiationAwareBeanPostProcessor的after方法。然后执行属性填充逻辑
5,属性填充后执行initializeBean方法,进行初始化,主要步骤为:BPP.before,InitializingBean.afterPropertiesSet或init-method,最后执行BPP的after方法

为什么被@Configuration修饰的类都创建了代理对象?
为了保持单例
比如@Bean修饰的方法里面创建的对象注入Spring容器后,如果还有其他的@Bean方法同样创建了这个对象,就不单例了
关注BeanMethodInterceptor类,拿cglib举例,该类重写的intercept增强方法,如果目标方法可以匹配到(isMatch),则会执行内部的getBean方法,Spring规定的Bean创建流程中会先从缓存中获取,没有才会创建。所以这是Spring创建代理对象的原因,在增强逻辑中控制对象的单例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值