一奕塑、回顧
上回講到spring在容器啟動(dòng)時(shí)需要?jiǎng)?chuàng)建一些單例bean械姻,創(chuàng)建單例bean的過(guò)程實(shí)際上就是spring創(chuàng)建bean實(shí)例的過(guò)程悍引,來(lái)回顧一下上次的代碼,不用全部看完恩脂,找到這次需要講到的createBeanInstance(beanName, mbd, args)方法即可
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// BeanWrrapper,Bean包裝器趣斤,簡(jiǎn)單理解成對(duì)bean賦值的俩块,后面展開(kāi)
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
//若mbd為單例,需要先判斷是否為FactoryBean
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
//如果instanceWrapper為空浓领,則創(chuàng)建一個(gè)bean實(shí)例
if (instanceWrapper == null) {
//createBeanInstance玉凯,創(chuàng)建bean實(shí)例封裝到wrapper中
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//通過(guò)wrapper獲取到了bean
final Object bean = instanceWrapper.getWrappedInstance();
//處理bean類型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// 允許post-processors修改mbd
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//簡(jiǎn)單來(lái)說(shuō)就是對(duì)mbd做一些加工
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
//拋出異常
......
}
mbd.postProcessed = true;
}
}
// 解決循環(huán)依賴的問(wèn)題
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
......
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// bean在實(shí)例化后,還需要賦值和初始化(init)
Object exposedObject = bean;
try {
//這一步負(fù)責(zé)屬性裝配镊逝,關(guān)鍵就在于BeanWrapper
populateBean(beanName, mbd, instanceWrapper);
//處理 bean 初始化完成后的各種回調(diào)
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
//拋出異常
......
}
//主要用于解決循環(huán)引用壮啊,這部分先跳過(guò)吧
if (earlySingletonExposure) {
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()) {
//拋出異常
......
}
}
}
}
// 注冊(cè)bean為使用后即銷毀
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
//拋出異常
......
}
return exposedObject;
}
二嫉鲸、createBeanInstance(beanName, mbd, args)
這個(gè)方法一看就很好理解撑蒜,創(chuàng)建bean實(shí)例,發(fā)現(xiàn)傳入了beanName,bean定義以及相關(guān)的參數(shù)用于執(zhí)行構(gòu)造函數(shù)座菠,跳轉(zhuǎn)到這個(gè)方法看一下
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 檢查class被load
Class<?> beanClass = resolveBeanClass(mbd, beanName);
//檢查beanClass
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提供bean實(shí)例
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
//由工廠方法創(chuàng)建bean實(shí)例
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// 這里表示創(chuàng)建已創(chuàng)建過(guò)的bean狸眼,判斷是通過(guò)無(wú)參構(gòu)造函數(shù),還是有參構(gòu)造函數(shù)依賴注入來(lái)完成實(shí)例化
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);
}
}
// 下面是第一次實(shí)例化bean的情況浴滴,首先判斷是否采用有參構(gòu)造函數(shù)
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// 有參構(gòu)造函數(shù)依賴注入并實(shí)例化bean
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// 無(wú)參構(gòu)造函數(shù)實(shí)例化bean
return instantiateBean(beanName, mbd);
}
三拓萌、bean的實(shí)例化
其實(shí)可以發(fā)現(xiàn),bean最終的實(shí)例化無(wú)非就是通過(guò)無(wú)參構(gòu)造方法或者有參構(gòu)造方法創(chuàng)建的即通過(guò)autowireConstructor方法和instantiateBean方法升略,由于前者的代碼很長(zhǎng)微王,以后有機(jī)會(huì)會(huì)專門寫一篇來(lái)講,這次先來(lái)看看后者instantiateBean
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
}
else {
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
不難發(fā)現(xiàn)bean是由getInstantiationStrategy().instantiate這一行關(guān)鍵代碼實(shí)現(xiàn)的品嚣,先來(lái)看看InstantiationStrategy是何方神圣
public interface InstantiationStrategy {
/**
* 默認(rèn)的構(gòu)造方法
*/
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)throws BeansException;
/**
* 指定構(gòu)造方法
*/
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
Constructor<?> ctor, Object... args) throws BeansException;
/**
* 通過(guò)指定的工廠方法
*/
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
@Nullable Object factoryBean, Method factoryMethod, Object... args)
throws BeansException;
簡(jiǎn)單來(lái)說(shuō)炕倘,InitiationStrategy提供了一系列通過(guò)構(gòu)造器來(lái)初始化bean實(shí)例的策略。
挑選默認(rèn)的構(gòu)造方法來(lái)看看spring是如何實(shí)現(xiàn)的把
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
//如果沒(méi)有方法被覆蓋,通過(guò)BeanUtils#instantiateClass來(lái)初始化(實(shí)質(zhì)是利用反射來(lái)創(chuàng)建)
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
//加鎖
synchronized (bd.constructorArgumentLock) {
//獲取構(gòu)造方法constructorToUse
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
//獲取Bean的class的對(duì)象
final Class<?> clazz = bd.getBeanClass();
//如果clazz是接口類型的,直接拋BeanInstantiationException異常
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
//在當(dāng)前系統(tǒng)安全模式的情況下
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
//獲取構(gòu)造方法
else {
constructorToUse = clazz.getDeclaredConstructor();
}
//將constructorToUse賦給resolvedConstructorOrFactoryMethod屬性
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
//通過(guò)BeanUtils直接使用構(gòu)造器對(duì)象實(shí)例化Bean對(duì)象
return BeanUtils.instantiateClass(constructorToUse);
}
else {
//生成CGLIB創(chuàng)建的子類對(duì)象
return instantiateWithMethodInjection(bd, beanName, owner);
}
}