IOC 单例Bean初始化

本文深入解析Spring框架中Bean的生命周期,从实例化单例对象开始,详细讲解了doGetBean方法如何初始化单例bean,包括从缓存获取单例对象、处理别名和循环依赖,以及createBean方法创建bean实例的过程。探讨了属性装配、初始化回调和销毁方法注册等关键步骤。
摘要由CSDN通过智能技术生成

组件

SimpleAliasRegistry

提供别名注册

public class SimpleAliasRegistry implements AliasRegistry {
	// 存放bean的别名  格式:(别名:Bean的ID名)
	// 未定义id,定义了多个Name,以第一个name为value
	// 未定义id和name,以类全限制名称+#0为value,全限制名称为key
	private final Map<String, String> aliasMap = new ConcurrentHashMap<>(16);
}

Converter

转换器,将传入的source转换为对应target

public interface Converter<S, T> {
	T convert(S source);
}

TypeConverter

定义类型转换方法的接口

public interface TypeConverter {
	// 将值转换为所需的类型
	<T> T convertIfNecessary(@Nullable Object value, @Nullable Class<T> requiredType) throws TypeMismatchException;
}

PropertyAccessor

属性访问器,用来存取Bean对象的属性

public interface PropertyAccessor {
	// 获得对应属性类型
	Class<?> getPropertyType(String propertyName) throws BeansException;
	// 获得对应属性值
	Object getPropertyValue(String propertyName) throws BeansException;
	// 设置对应属性值
	void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException;
}

PropertyEditorSupport

属性编辑器,使用户可以通过给定类型来编辑属性

public interface PropertyEditorSupport {
	private Object value;
	private Object source;
	// 属性变动的监听器
	private java.util.Vector<PropertyChangeListener> listeners;

	void setValue(Object value);
	// 通过给定string值设置属性值
	void setAsText(String text) throws java.lang.IllegalArgumentException;
	
	Object getValue();
	// 获得属性值的string表示
	String getAsText();
}

PropertyEditorRegistrySupport

提供对默认编辑器和自定义编辑器的管理

public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
	// 持有的属性编辑器
	@Nullable
	private Map<Class<?>, PropertyEditor> defaultEditors;
	@Nullable
	private Map<Class<?>, PropertyEditor> overriddenDefaultEditors;
	@Nullable
	private Map<Class<?>, PropertyEditor> customEditors;
	@Nullable
	private Map<String, CustomEditorHolder> customEditorsForPath;
	@Nullable
	private Map<Class<?>, PropertyEditor> customEditorCache;
	
	// 注册属性编辑器
	void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor);
	// 获得属性编辑器
	PropertyEditor findCustomEditor(@Nullable Class<?> requiredType, @Nullable String propertyPath);
}	

BeanWrapper

Spring底层JavaBeans基础设施的中央接口

public interface BeanWrapper extends ConfigurablePropertyAccessor {
	// 返回这个对象包装的bean实例
	Object getWrappedInstance();
	// 指定数组和集合自动增长的限制
	void setAutoGrowCollectionLimit(int autoGrowCollectionLimit);
}

源码解析

1. 实例化单例对象(DefaultListableBeanFactory)

  • 遍历所有xml中定义的bean,bean为单例、非抽象、非懒加载
  • 对于普通bean直接调用getBean(name),对于工厂bean调用getBean(&+name)
  • 完成初始化后,如果bean实现了SmartInitializingSingleton则执行其afterSingletonsInstantiated方法
public void preInstantiateSingletons() throws BeansException {
	···日志

	// 获得IOC容器中beanNames(也就是xml中<bean id="XX">的id)
	List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

	// 触发所有非延迟单例bean的初始化
	for (String beanName : beanNames) {
		// 获得合并后的bd
		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
		// 单例、非抽象、非懒加载
		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
			// 如果是工厂bean实例则添加&前缀,调用getBean实例化
			if (isFactoryBean(beanName)) {
				Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
				// 判断是否为SmartFactoryBean
				if (bean instanceof FactoryBean) {
					final 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 {
				// 普通bean初始化
				getBean(beanName);
			}
		}
	}

	// 遍历beanNames,触发所有SmartInitializingSingleton的后初始化回调
	for (String beanName : beanNames) {
		Object singletonInstance = getSingleton(beanName);
		if (singletonInstance instanceof SmartInitializingSingleton) {
			final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
			if (System.getSecurityManager() != null) {
				AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
					smartSingleton.afterSingletonsInstantiated();
					return null;
				}, getAccessControlContext());
			}
			else {
				smartSingleton.afterSingletonsInstantiated();
			}
		}
	}
}

2. doGetBean初始单例bean(AbstractBeanFactory)

  • beanName转换,首先如果为工厂名先从transformedBeanNameCache中获取真实beanName,然后从AliasMap中取真实beanId
  • 从缓存中获得单例bean的引用,如果引用不为空且参数传入为空,直接使用缓存中的实例作为返回值
  • 存在父工厂且当前工厂不包含改beanName则调用父工厂的doGetBean来获得实例
  • 判断typeCheckOnly将当前beanName放入alreadyCreated集合中(用来判断bean是否正在创建中)
  • 检查是否存在depends-on,优先加载
  • 判断是否为singleton和prototype,分别执行createBean方法创建bean实例
  • 如果requiredType存在,则检查返回实例是否满足requiredType
public Object getBean(String name) throws BeansException {
	return doGetBean(name, null, null, false);
}
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
	// 对传递进来的beanName转换(处理别名和带&的工厂bean名)
	final String beanName = transformedBeanName(name);
	Object bean;

	// 检查单例缓存中注册的单例
	Object sharedInstance = getSingleton(beanName);
	// 如果缓存不存在引用且传递参数为空(为空表示获取,不为空表示希望创建bean)
	if (sharedInstance != null && args == null) {
		···日志打印
		// 普通bean直接返回,工厂bean返回工厂创建的实例对象
		bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
	}
	// 进入bean创建逻辑
	else {
		// 如果当前线程创建的prototype类型的bean已在创建中,抛出异常
		if (isPrototypeCurrentlyInCreation(beanName)) {
			throw new BeanCurrentlyInCreationException(beanName);
		}

		
		BeanFactory parentBeanFactory = getParentBeanFactory();
		// 检查bd是否在父工厂中存在且当前工厂不包含beanName
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			// 获得原始的bean名称
			String nameToLookup = originalBeanName(name);
			// 父工厂调用doGetBean获得实例
			if (parentBeanFactory instanceof AbstractBeanFactory) {
				return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
						nameToLookup, requiredType, args, typeCheckOnly);
			}
			else if (args != null) {
				// Delegation to parent with explicit args.
				return (T) parentBeanFactory.getBean(nameToLookup, args);
			}
			else if (requiredType != null) {
				// No args -> delegate to standard getBean method.
				return parentBeanFactory.getBean(nameToLookup, requiredType);
			}
			else {
				return (T) parentBeanFactory.getBean(nameToLookup);
			}
		}
		// 将当前beanName放入alreadyCreated中
		if (!typeCheckOnly) {
			markBeanAsCreated(beanName);
		}

		try {
			// 获得bd,并检查mbd是否为抽象类
			final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
			checkMergedBeanDefinition(mbd, beanName, args);

			// 确保当前bean所依赖的bean都已经初始化好了
			String[] dependsOn = mbd.getDependsOn();
			if (dependsOn != null) {
				for (String dep : dependsOn) {
					// 从dependentBeanMap中检查是否存在循环的depends-on
					if (isDependent(beanName, dep)) {
						throw new BeanCreationException(mbd.getResourceDescription(), beanName,
								"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
					}
					// 在dependentBeanMap注册依赖
					registerDependentBean(dep, beanName);
					try {
						// 获得依赖实例
						getBean(dep);
					}
					···异常抛出
				}
			}

			// 创建bean实例,如果bean为单例createBean
			if (mbd.isSingleton()) {
				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);
			}
			// 如果为prototype
			else if (mbd.isPrototype()) {
				// It's a prototype -> create a new instance.
				Object prototypeInstance = null;
				try {
					// 将当前原型类型加入正在创建中
					beforePrototypeCreation(beanName);
					prototypeInstance = createBean(beanName, mbd, args);
				}
				finally {
					afterPrototypeCreation(beanName);
				}
				bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
			}
			// 如果不为prototype和singleton则委托给相应的实现类来处理
			else {
				String scopeName = mbd.getScope();
				final Scope scope = this.scopes.get(scopeName);
				if (scope == null) {
					throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
				}
				try {
					Object scopedInstance = scope.get(beanName, () -> {
						beforePrototypeCreation(beanName);
						try {
							return createBean(beanName, mbd, args);
						}
						finally {
							afterPrototypeCreation(beanName);
						}
					});
					bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
				}
				catch (IllegalStateException ex) {
					throw new BeanCreationException(beanName,
							"Scope '" + scopeName + "' is not active for the current thread; consider " +
							"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
							ex);
				}
			}
		}
		catch (BeansException ex) {
			cleanupAfterBeanCreationFailure(beanName);
			throw ex;
		}
	}

	// 检查要求类型是否与bean类型一致
	if (requiredType != null && !requiredType.isInstance(bean)) {
		try {
			// 不一致进行类型转换
			T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
			if (convertedBean == null) {
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
			return convertedBean;
		}
		···打印日志抛出异常
	}
	return (T) bean;
}
2.1 获得单例对象缓存(从3级缓存获取)

singletonFactories:存放刚初始化的单例对象工厂,解决循环依赖
earlySingletonObjects:存放刚初始化还未配置属性和初始化的bean
singletonObjects:存放初始好的bean
Set singletonsCurrentlyInCreation:存放正在创建中的bean名称

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	// 从1级缓存获取已经初始化完成的bean
	Object singletonObject = this.singletonObjects.get(beanName);
	// 如果1级缓存不存在,且当前bean正在创建中
	if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
		// 多线程同步锁,一个线程进入后,其他线程就能直接从缓存取
		synchronized (this.singletonObjects) {
			// 从2级缓存从获取对象实例
			singletonObject = this.earlySingletonObjects.get(beanName);
			// 如果仍为空且创建早期引用标识为true,从3级缓存获取
			if (singletonObject == null && allowEarlyReference) {
				// 获得单例工厂
				ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
				// 工厂不为空将3级缓存升级到2级缓存
				if (singletonFactory != null) {
					singletonObject = singletonFactory.getObject();
					this.earlySingletonObjects.put(beanName, singletonObject);
					this.singletonFactories.remove(beanName);
				}
			}
		}
	}
	return singletonObject;
}

3. createBean(AbstractAutowireCapableBeanFactory)

  • 首先确保beanclass被加载
  • 处理 lookup-method 和 replace-method
  • InstantiationAwareBeanPostProcessor实现类处理
  • 调用doCreateBean创建实例
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
	···日志打印
	RootBeanDefinition mbdToUse = mbd;

	// 确保beanclass被加载
	Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
	if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
		mbdToUse = new RootBeanDefinition(mbd);
		mbdToUse.setBeanClass(resolvedClass);
	}

	// 准备方法复写,就是处理 lookup-method 和 replace-method
	// lookup-method:解决注入的prototype类型被缓存(p1==p2返回true,不符合prototype定义) <lookup-method name="方法名(抽象)" bean="bean引用名"/>
	// replace-method:通过实现MethodReplacer接口完成对原类方法的替换  <replaced-method name="方法名" replacer="替换类引用名"/>
	try {
		mbdToUse.prepareMethodOverrides();
	}
	···异常抛出

	try {
		// 实现InstantiationAwareBeanPostProcessor的类型在这可以返回代理对象
		// 如果postProcessBeforeInstantiation方法返回值不为null,则直接调用postProcessAfterInstantiation方法,不为空跳过doCreateBean(AOP生成代理对象)
		Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
		if (bean != null) {
			return bean;
		}
	}
	···异常抛出

	try {
		// 创建bean实例
		Object beanInstance = doCreateBean(beanName, mbdToUse, args);
		···日志打印
		return beanInstance;
	}
	···异常抛出
}

4. doCreateBean创建bean实例(AbstractAutowireCapableBeanFactory)

  • createBeanInstance创建bean实例
  • MergedBeanDefinitionPostProcessor接口处理
  • 解决循环依赖
  • 完成实例属性装配和初始完成后的回调
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {

	// 定义Bean实例
	BeanWrapper instanceWrapper = null;
	// 如果为单例从工厂Bean缓存缓存移除实例
	if (mbd.isSingleton()) {
		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
	}
	if (instanceWrapper == null) {
		// 创建bean实例
		instanceWrapper = createBeanInstance(beanName, mbd, args);
	}
	// 获得bean实例及其类型
	final Object bean = instanceWrapper.getWrappedInstance();
	Class<?> beanType = instanceWrapper.getWrappedClass();
	if (beanType != NullBean.class) {
		mbd.resolvedTargetType = beanType;
	}

	// MergedBeanDefinitionPostProcessor接口处理(@Autowired和@Value解析会用到)
	synchronized (mbd.postProcessingLock) {
		if (!mbd.postProcessed) {
			try {
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
			}
			catch (Throwable ex) {
				throw new BeanCreationException(mbd.getResourceDescription(), beanName,
						"Post-processing of merged bean definition failed", ex);
			}
			mbd.postProcessed = true;
		}
	}

	// 解决循环依赖,如果为单例、允许循环依赖且bean正在创建中
	boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
			isSingletonCurrentlyInCreation(beanName));
	if (earlySingletonExposure) {
		···日志
		// 如果beanName不存在singletonObjects中,singletonFactories添加对象,earlySingletonObjects移除
		addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
	}

	// 初始bean实例
	Object exposedObject = bean;
	try {
		// 完成实例的属性装配
		populateBean(beanName, mbd, instanceWrapper);
		// 处理bean初始化完成后的各种回调, init-method BeanPostProcessor InitializingBean 
		exposedObject = initializeBean(beanName, exposedObject, mbd);
	}
	···异常抛出

	if (earlySingletonExposure) {
		Object earlySingletonReference = getSingleton(beanName, false);
		// 存在循环依赖,如A->B,B->A,A在创建中依赖B,A在populateBean实例化B,B实例化完成持有A的初始引用XXX1
		// 如果经过initializeBean方法A对象实例改变为XXX2,导致B中持有A的依赖XXX1与当前A的依赖不一致则抛出异常
		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.");
				}
			}
		}
	}

	// 注册bean自定义销毁方法,DisposableBean destroy-method @PreDestroy
	try {
		registerDisposableBeanIfNecessary(beanName, bean, mbd);
	}
	···异常抛出

	return exposedObject;
}
4.1 获得实例属性值,装配属性
  • InstantiationAwareBeanPostProcessors判断该bean属性是否需要被注入
  • 如果设置了自动装配采用自动装配获得属性
  • InstantiationAwareBeanPostProcessors注入属性(@Autowired和@Value注解实现)
  • 依赖检查
  • applyPropertyValues为实例填充属性(对属性值进行解析类型转换)
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
	// 实例为null则直接返回(存在属性则抛出异常)
	if (bw == null) {
		if (mbd.hasPropertyValues()) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
		}
		else {
			// Skip property population phase for null instance.
			return;
		}
	}

	// InstantiationAwareBeanPostProcessors修改属性值(在注入属性前)
	if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof InstantiationAwareBeanPostProcessor) {
				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
				if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
					return;
				}
			}
		}
	}
	// 获得需要注入的属性
	PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

	int resolvedAutowireMode = mbd.getResolvedAutowireMode();
	// 如果为类型或名称自动装配
	if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
		// 根据名称装配属性(遍历属性名,getBean)
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
			autowireByName(beanName, mbd, bw, newPvs);
		}
		// 根据类型装配属性
		if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
			autowireByType(beanName, mbd, bw, newPvs);
		}
		pvs = newPvs;
	}
	// 如果存在InstantiationAwareBeanPostProcessor
	boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
	// 需要依赖检查
	boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

	PropertyDescriptor[] filteredPds = null;
	// 如果存在InstantiationAwareBeanPostProcessor 
	if (hasInstAwareBpps) {
		if (pvs == null) {
			pvs = mbd.getPropertyValues();
		}
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			// @Autowired和@Value注解就是通过AutowiredAnnotationBeanPostProcessor实现属性注入的
			if (bp instanceof InstantiationAwareBeanPostProcessor) {
				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
				// 先调用postProcessProperties方法
				PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
				if (pvsToUse == null) {
					if (filteredPds == null) {
						filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
					}
					// 未找到再调用deprecate方法postProcessPropertyValues
					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);
	}

	if (pvs != null) {
		applyPropertyValues(beanName, mbd, bw, pvs);
	}
}
4.2 实例初始化完成后的回调
  • 3个Aware接口设置
  • BeanPostProcessor处理,调用postProcessBeforeInitialization方法
  • init-method或InitializingBean接口afterPropertiesSet方法调用
  • BeanPostProcessor处理,调用postProcessAfterInitialization方法
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
	// 如果bean实现了这三个接口BeanNameAware、BeanClassLoaderAware和BeanFactoryAware,则设置对应值
	if (System.getSecurityManager() != null) {
		AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
			invokeAwareMethods(beanName, bean);
			return null;
		}, getAccessControlContext());
	}
	else {
		invokeAwareMethods(beanName, bean);
	}

	Object wrappedBean = bean;
	// BeanPostProcessor处理,如果返回null后续BeanPostProcessor都不处理
	if (mbd == null || !mbd.isSynthetic()) {
		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
	}

	try {
		// init-method方法处理
		// InitializingBean接口调用afterPropertiesSet方法
		invokeInitMethods(beanName, wrappedBean, mbd);
	}
	···异常抛出
	// BeanPostProcessor处理,如果返回null后续BeanPostProcessor都不处理
	if (mbd == null || !mbd.isSynthetic()) {
		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
	}

	return wrappedBean;
}
4.3 注册销毁方法
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
	AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
	// 如果当前bean不为原型且存在销毁方法
	if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
		// 为单例
		if (mbd.isSingleton()) {
			// 注册DisposableBean实例来处理DestructionAwareBeanPostProcessors,
			// DisposableBean接口, destroy-method.
			registerDisposableBean(beanName,
					new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
		}
		else {
			// 其他范围
			Scope scope = this.scopes.get(mbd.getScope());
			if (scope == null) {
				throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
			}
			scope.registerDestructionCallback(beanName,
					new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
		}
	}
}

5. createBeanInstance创建bean实例(AbstractAutowireCapableBeanFactory)

  • 确保beanclass被加载,校验类访问权限
  • 通过supplier接口获得实例,通过工厂方法获得实例(优先加载factory-bean类)
  • 重复加载快捷方式
  • SmartInstantiationAwareBeanPostProcessor接口处理
  • 默认构造注入,如果有method override使用cglib生成代理类,否则使用java反射通过默认构造方法创建类实例
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
	// 确保beanclass被加载
	Class<?> beanClass = resolveBeanClass(mbd, beanName);
	// 校验类访问权限
	if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
		throw new BeanCreationException(mbd.getResourceDescription(), beanName,
				"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
	}
	// 通过Supplier接口获得实例
	Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
	if (instanceSupplier != null) {
		return obtainFromSupplier(instanceSupplier, beanName);
	}
	// 通过工厂方法获得实例,factory-method,factory-bean,如果factory-bean还没实例化则先实例化
	if (mbd.getFactoryMethodName() != null) {
		return instantiateUsingFactoryMethod(beanName, mbd, args);
	}

	// 重新创建同一个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);
		}
		 // 默认构造注入,如果有method override使用cglib生成代理类,否则使用java反射通过默认构造方法创建类实例
		else {
			return instantiateBean(beanName, mbd);
		}
	}

	// 判断是否采用有参构造函数,SmartInstantiationAwareBeanPostProcessor接口处理
	Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
	if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
			mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
		return autowireConstructor(beanName, mbd, ctors, args);
	}

	// 默认构造的首选构造函数,子类实现
	ctors = mbd.getPreferredConstructors();
	if (ctors != null) {
		return autowireConstructor(beanName, mbd, ctors, null);
	}

	// 采用默认构造
	return instantiateBean(beanName, mbd);
}

总结

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值