Spring 自動(dòng)裝配之依賴注入
依賴注入發(fā)生的時(shí)間
當(dāng)Spring IOC 容器完成了Bean 定義資源的定位、載入和解析注冊(cè)以后言疗,IOC 容器中已經(jīng)管理類Bean定義的相關(guān)數(shù)據(jù)恳邀,但是此時(shí)IOC 容器還沒有對(duì)所管理的Bean 進(jìn)行依賴注入懦冰,依賴注入在以下兩種情況發(fā)生:
1)、用戶第一次調(diào)用getBean()方法時(shí)谣沸,IOC 容器觸發(fā)依賴注入刷钢。
2)、當(dāng)用戶在配置文件中將<bean>元素配置了lazy-init=false 屬性乳附,即讓容器在解析注冊(cè)Bean 定義時(shí)進(jìn)行預(yù)實(shí)例化闯捎,觸發(fā)依賴注入。
BeanFactory 接口定義了Spring IOC 容器的基本功能規(guī)范许溅,是Spring IOC 容器所應(yīng)遵守的最底層和最基本的編程規(guī)范。BeanFactory 接口中定義了幾個(gè)getBean()方法秉版,就是用戶向IOC 容器索取管理的Bean 的方法贤重,我們通過分析其子類的具體實(shí)現(xiàn),理解Spring IOC 容器在用戶索取Bean 時(shí)如何完成依賴注入清焕。
在BeanFactory 中我們可以看到getBean(String...)方法并蝗,但它具體實(shí)現(xiàn)在AbstractBeanFactory 中祭犯。
尋找獲取Bean 的入口
AbstractBeanFactory 的getBean()相關(guān)方法的源碼如下:
//獲取IOC 容器中指定名稱的Bean
@Override
public Object getBean(String name) throws BeansException {
//doGetBean 才是真正向IOC 容器獲取被管理Bean 的過程
return doGetBean(name, null, null, false);
}
//獲取IOC 容器中指定名稱和類型的Bean
@Override
public <T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException {
//doGetBean 才是真正向IOC 容器獲取被管理Bean 的過程
return doGetBean(name, requiredType, null, false);
}
//獲取IOC 容器中指定名稱和參數(shù)的Bean
@Override
public Object getBean(String name, Object... args) throws BeansException {
//doGetBean 才是真正向IOC 容器獲取被管理Bean 的過程
return doGetBean(name, null, args, false);
}
//獲取IOC 容器中指定名稱、類型和參數(shù)的Bean
public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args)
throws BeansException {
//doGetBean 才是真正向IOC 容器獲取被管理Bean 的過程
return doGetBean(name, requiredType, args, false);
}
@SuppressWarnings("unchecked")
//真正實(shí)現(xiàn)向IOC 容器獲取Bean 的功能滚停,也是觸發(fā)依賴注入功能的地方
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
//根據(jù)指定的名稱獲取被管理Bean 的名稱沃粗,剝離指定名稱中對(duì)容器的相關(guān)依賴
//如果指定的是別名,將別名轉(zhuǎn)換為規(guī)范的Bean 名稱
final String beanName = transformedBeanName(name);
Object bean;
//先從緩存中取是否已經(jīng)有被創(chuàng)建過的單態(tài)類型的Bean
//對(duì)于單例模式的Bean 整個(gè)IOC 容器中只創(chuàng)建一次键畴,不需要重復(fù)創(chuàng)建
Object sharedInstance = getSingleton(beanName);
//IOC 容器創(chuàng)建單例模式Bean 實(shí)例對(duì)象
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
//如果指定名稱的Bean 在容器中已有單例模式的Bean 被創(chuàng)建
//直接返回已經(jīng)創(chuàng)建的Bean
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
} else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
//獲取給定Bean 的實(shí)例對(duì)象最盅,主要是完成FactoryBean 的相關(guān)處理
//注意:BeanFactory 是管理容器中Bean 的工廠,而FactoryBean 是
//創(chuàng)建創(chuàng)建對(duì)象的工廠Bean起惕,兩者之間有區(qū)別
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
//緩存沒有正在創(chuàng)建的單例模式Bean
//緩存中已經(jīng)有已經(jīng)創(chuàng)建的原型模式Bean
//但是由于循環(huán)引用的問題導(dǎo)致實(shí)例化對(duì)象失敗
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
//對(duì)IOC 容器中是否存在指定名稱的BeanDefinition 進(jìn)行檢查涡贱,首先檢查是否
//能在當(dāng)前的BeanFactory 中獲取的所需要的Bean,如果不能則委托當(dāng)前容器
//的父級(jí)容器去查找惹想,如果還是找不到則沿著容器的繼承體系向父級(jí)容器查找
BeanFactory parentBeanFactory = getParentBeanFactory();
//當(dāng)前容器的父級(jí)容器存在问词,且當(dāng)前容器中不存在指定名稱的Bean
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
//解析指定Bean 名稱的原始名稱
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
} else if (args != null) {
//委派父級(jí)容器根據(jù)指定名稱和顯式的參數(shù)查找
return (T) parentBeanFactory.getBean(nameToLookup, args);
} else {
//委派父級(jí)容器根據(jù)指定名稱和類型查找
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
//創(chuàng)建的Bean 是否需要進(jìn)行類型驗(yàn)證,一般不需要
if (!typeCheckOnly) {
//向容器標(biāo)記指定的Bean 已經(jīng)被創(chuàng)建
markBeanAsCreated(beanName);
}
try {
//根據(jù)指定Bean 名稱獲取其父級(jí)的Bean 定義
//主要解決Bean 繼承時(shí)子類合并父類公共屬性問題
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
//獲取當(dāng)前Bean 所有依賴Bean 的名稱
String[] dependsOn = mbd.getDependsOn();
//如果當(dāng)前Bean 有依賴Bean
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
//遞歸調(diào)用getBean 方法嘀粱,獲取當(dāng)前Bean 的依賴Bean
registerDependentBean(dep, beanName);
//把被依賴Bean 注冊(cè)給當(dāng)前依賴的Bean
getBean(dep);
}
}
//創(chuàng)建單例模式Bean 的實(shí)例對(duì)象
if (mbd.isSingleton()) {
//這里使用了一個(gè)匿名內(nèi)部類激挪,創(chuàng)建Bean 實(shí)例對(duì)象,并且注冊(cè)給所依賴的對(duì)象
sharedInstance = getSingleton(beanName, () -> {
try {
//創(chuàng)建一個(gè)指定Bean 實(shí)例對(duì)象锋叨,如果有父級(jí)繼承垄分,則合并子類和父類的定義
return createBean(beanName, mbd, args);
} catch (BeansException ex) {
//顯式地從容器單例模式Bean 緩存中清除實(shí)例對(duì)象
destroySingleton(beanName);
throw ex;
}
});
//獲取給定Bean 的實(shí)例對(duì)象
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
//IOC 容器創(chuàng)建原型模式Bean 實(shí)例對(duì)象
else if (mbd.isPrototype()) {
//原型模式(Prototype)是每次都會(huì)創(chuàng)建一個(gè)新的對(duì)象
Object prototypeInstance = null;
try {
//回調(diào)beforePrototypeCreation 方法,默認(rèn)的功能是注冊(cè)當(dāng)前創(chuàng)建的原型對(duì)象
beforePrototypeCreation(beanName);
//創(chuàng)建指定Bean 對(duì)象實(shí)例
prototypeInstance = createBean(beanName, mbd, args);
} finally {
//回調(diào)afterPrototypeCreation 方法悲柱,默認(rèn)的功能告訴IOC 容器指定Bean 的原型對(duì)象不再創(chuàng)建
afterPrototypeCreation(beanName);
}
//獲取給定Bean 的實(shí)例對(duì)象
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
//要?jiǎng)?chuàng)建的Bean 既不是單例模式锋喜,也不是原型模式,則根據(jù)Bean 定義資源中
//配置的生命周期范圍豌鸡,選擇實(shí)例化Bean 的合適方法嘿般,這種在Web 應(yīng)用程序中
//比較常用,如:request涯冠、session炉奴、application 等生命周期
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
//Bean 定義資源中沒有配置生命周期范圍,則Bean 定義不合法
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
//這里又使用了一個(gè)匿名內(nèi)部類蛇更,獲取一個(gè)指定生命周期范圍的實(shí)例
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
} finally {
afterPrototypeCreation(beanName);
}
});
//獲取給定Bean 的實(shí)例對(duì)象
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;
}
}
//對(duì)創(chuàng)建的Bean 實(shí)例對(duì)象進(jìn)行類型檢查
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;
} catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
通過上面對(duì)向IOC 容器獲取Bean 方法的分析瞻赶,我們可以看到在Spring 中,如果Bean 定義的單例模式(Singleton)派任,則容器在創(chuàng)建之前先從緩存中查找砸逊,以確保整個(gè)容器中只存在一個(gè)實(shí)例對(duì)象。如果Bean定義的是原型模式(Prototype)掌逛,則容器每次都會(huì)創(chuàng)建一個(gè)新的實(shí)例對(duì)象师逸。除此之外,Bean 定義還可以擴(kuò)展為指定其生命周期范圍豆混。
上面的源碼只是定義了根據(jù)Bean 定義的模式篓像,采取的不同創(chuàng)建Bean 實(shí)例對(duì)象的策略动知,具體的Bean實(shí)例對(duì)象的創(chuàng)建過程由實(shí)現(xiàn)了ObjectFactory 接口的匿名內(nèi)部類的createBean() 方法完成,ObjectFactory 使用委派模式员辩, 具體的Bean 實(shí)例創(chuàng)建過程交由其實(shí)現(xiàn)類AbstractAutowireCapableBeanFactory 完成盒粮,我們繼續(xù)分析AbstractAutowireCapableBeanFactory的createBean()方法的源碼,理解其創(chuàng)建Bean 實(shí)例的具體實(shí)現(xiàn)過程奠滑。
開始實(shí)例化
AbstractAutowireCapableBeanFactory 類實(shí)現(xiàn)了ObjectFactory 接口丹皱,創(chuàng)建容器指定的Bean 實(shí)例對(duì)象,同時(shí)還對(duì)創(chuàng)建的Bean 實(shí)例對(duì)象進(jìn)行初始化處理养叛。其創(chuàng)建Bean 實(shí)例對(duì)象的方法源碼如下:
//創(chuàng)建Bean 實(shí)例對(duì)象
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
//判斷需要?jiǎng)?chuàng)建的Bean 是否可以實(shí)例化种呐,即是否可以通過當(dāng)前的類加載器加載
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
//校驗(yàn)和準(zhǔn)備Bean 中的方法覆蓋
try {
mbdToUse.prepareMethodOverrides();
} catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of Method overrides failed", ex);
}
try {
//如果Bean 配置了初始化前和初始化后的處理器,則試圖返回一個(gè)需要?jiǎng)?chuàng)建Bean 的代理對(duì)象
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
} catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
//創(chuàng)建Bean 的入口
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
} catch (BeanCreationException ex) {
throw ex;
} catch (ImplicitlyAppearedSingletonException ex) {
throw ex;
} catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
//真正創(chuàng)建Bean 的方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
//封裝被創(chuàng)建的Bean 對(duì)象
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
//獲取實(shí)例化對(duì)象的類型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
//調(diào)用PostProcessor 后置處理器
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 對(duì)象弃甥,以防循環(huán)引用
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//這里是一個(gè)匿名內(nèi)部類爽室,為了防止循環(huán)引用,盡早持有對(duì)象的引用
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
//Bean 對(duì)象的初始化淆攻,依賴注入在此觸發(fā)
//這個(gè)exposedObject 在初始化完成之后返回作為依賴注入完成后的Bean
Object exposedObject = bean;
try {
//將Bean 實(shí)例對(duì)象封裝阔墩,并且Bean 定義中配置的屬性值賦值給實(shí)例對(duì)象
populateBean(beanName, mbd, instanceWrapper);
//初始化Bean 對(duì)象
exposedObject = initializeBean(beanName, exposedObject, mbd);
} catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
} else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
//獲取指定名稱的已注冊(cè)的單例模式Bean 對(duì)象
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
//根據(jù)名稱獲取的已注冊(cè)的Bean 和正在實(shí)例化的Bean 是同一個(gè)
if (exposedObject == bean) {
//當(dāng)前實(shí)例化的Bean 初始化完成
exposedObject = earlySingletonReference;
}
//當(dāng)前Bean 依賴其他Bean,并且當(dāng)發(fā)生循環(huán)引用時(shí)不允許新創(chuàng)建實(shí)例對(duì)象
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
//獲取當(dāng)前Bean 所依賴的其他Bean
for (String dependentBean : dependentBeans) {
//對(duì)依賴Bean 進(jìn)行類型檢查
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 " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
//注冊(cè)完成依賴注入的Bean
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
} catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
通過上面的源碼注釋瓶珊,我們看到具體的依賴注入實(shí)現(xiàn)其實(shí)就在以下兩個(gè)方法中:
1)啸箫、createBeanInstance()方法,生成Bean 所包含的java 對(duì)象實(shí)例伞芹。
2)忘苛、populateBean()方法,對(duì)Bean 屬性的依賴注入進(jìn)行處理唱较。
下面繼續(xù)分析這兩個(gè)方法的代碼實(shí)現(xiàn)扎唾。
選擇Bean 實(shí)例化策略
在createBeanInstance()方法中,根據(jù)指定的初始化策略南缓,使用簡(jiǎn)單工廠胸遇、工廠方法或者容器的自動(dòng)裝配特性生成Java 實(shí)例對(duì)象,創(chuàng)建對(duì)象的源碼如下:
//創(chuàng)建Bean 的實(shí)例對(duì)象
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
//檢查確認(rèn)Bean 是可實(shí)例化的
Class<?> beanClass = resolveBeanClass(mbd, beanName);
//使用工廠方法對(duì)Bean 進(jìn)行實(shí)例化
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<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
if (mbd.getFactoryMethodName() != null) {
//調(diào)用工廠方法實(shí)例化
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
//使用容器的自動(dòng)裝配方法進(jìn)行實(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) {
//配置了自動(dòng)裝配屬性汉形,使用容器的自動(dòng)裝配實(shí)例化
//容器的自動(dòng)裝配是根據(jù)參數(shù)類型匹配Bean 的構(gòu)造方法
return autowireConstructor(beanName, mbd, null, null);
} else {
//使用默認(rèn)的無參構(gòu)造方法實(shí)例化
return instantiateBean(beanName, mbd);
}
}
//使用Bean 的構(gòu)造方法進(jìn)行實(shí)例化
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
//使用容器的自動(dòng)裝配特性纸镊,調(diào)用匹配的構(gòu)造方法實(shí)例化
return autowireConstructor(beanName, mbd, ctors, args);
}
//使用默認(rèn)的無參構(gòu)造方法實(shí)例化
return instantiateBean(beanName, mbd);
}
//使用默認(rèn)的無參構(gòu)造方法實(shí)例化Bean 對(duì)象
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
//獲取系統(tǒng)的安全管理接口,JDK 標(biāo)準(zhǔn)的安全管理API
if (System.getSecurityManager() != null) {
//這里是一個(gè)匿名內(nèi)置類概疆,根據(jù)實(shí)例化策略創(chuàng)建實(shí)例對(duì)象
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
} else {
//將實(shí)例化的對(duì)象封裝起來
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);
}
}
經(jīng)過對(duì)上面的代碼分析逗威,我們可以看出,對(duì)使用工廠方法和自動(dòng)裝配特性的Bean 的實(shí)例化相當(dāng)比較清楚岔冀,調(diào)用相應(yīng)的工廠方法或者參數(shù)匹配的構(gòu)造方法即可完成實(shí)例化對(duì)象的工作庵楷,但是對(duì)于我們最常使用的默認(rèn)無參構(gòu)造方法就需要使用相應(yīng)的初始化策略(JDK 的反射機(jī)制或者CGLib)來進(jìn)行初始化了,在方法getInstantiationStrategy().instantiate()中就具體實(shí)現(xiàn)類使用初始策略實(shí)例化象。
執(zhí)行Bean 實(shí)例化
在使用默認(rèn)的無參構(gòu)造方法創(chuàng)建Bean 的實(shí)例化對(duì)象時(shí)尽纽,方法getInstantiationStrategy().instantiate()調(diào)用了SimpleInstantiationStrategy 類中的實(shí)例化Bean 的方法,其源碼如下:
//使用初始化策略實(shí)例化Bean 對(duì)象
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// Don't override the class with CGLib if no overrides.
//如果Bean 定義中沒有方法覆蓋童漩,則就不需要CGLib 父類類的方法
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
//獲取對(duì)象的構(gòu)造方法或工廠方法
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
//如果沒有構(gòu)造方法且沒有工廠方法
if (constructorToUse == null) {
//使用JDK 的反射機(jī)制弄贿,判斷要實(shí)例化的Bean 是否是接口
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
//這里是一個(gè)匿名內(nèi)置類,使用反射機(jī)制獲取Bean 的構(gòu)造方法
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) () -> clazz.getDeclaredConstructor());
} else {
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
} catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
//使用BeanUtils 實(shí)例化矫膨,通過反射機(jī)制調(diào)用”構(gòu)造方法.newInstance(arg)”來進(jìn)行實(shí)例化
return BeanUtils.instantiateClass(constructorToUse);
} else {
// Must generate CGLib subclass.
//使用CGLib 來實(shí)例化對(duì)象
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
通過上面的代碼分析差凹,我們看到了如果Bean 有方法被覆蓋了,則使用JDK 的反射機(jī)制進(jìn)行實(shí)例化侧馅,否則危尿,使用CGLib 進(jìn)行實(shí)例化。
instantiateWithMethodInjection() 方法調(diào)用SimpleInstantiationStrategy 的子類CGLibSubclassingInstantiationStrategy 使用CGLib 來進(jìn)行初始化馁痴,其源碼如下:
//使用CGLib 進(jìn)行Bean 對(duì)象實(shí)例化
public Object instantiate(@Nullable Constructor<?> ctor, @Nullable Object... args) {
//創(chuàng)建代理子類
Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
Object instance;
if (ctor == null) {
instance = BeanUtils.instantiateClass(subclass);
} else {
try {
Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
instance = enhancedSubclassConstructor.newInstance(args);
} catch (Exception ex) {
throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
"Failed to invoke constructor for CGLib enhanced subclass [" + subclass.getName() + "]", ex);
}
}
Factory factory = (Factory) instance;
factory.setCallbacks(new Callback[]{NoOp.INSTANCE,
new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
return instance;
}
private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) {
//CGLib 中的類
Enhancer enhancer = new Enhancer();
//將Bean 本身作為其基類
enhancer.setSuperclass(beanDefinition.getBeanClass());
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
if (this.owner instanceof ConfigurableBeanFactory) {
ClassLoader cl = ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
}
enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
enhancer.setCallbackTypes(CALLBACK_TYPES);
//使用CGLib 的createClass 方法生成實(shí)例對(duì)象
return enhancer.createClass();
}
CGLib 是一個(gè)常用的字節(jié)碼生成器的類庫(kù)谊娇,它提供了一系列API 實(shí)現(xiàn)Java 字節(jié)碼的生成和轉(zhuǎn)換功能。我們?cè)趯W(xué)習(xí)JDK 的動(dòng)態(tài)代理時(shí)都知道罗晕,JDK 的動(dòng)態(tài)代理只能針對(duì)接口济欢,如果一個(gè)類沒有實(shí)現(xiàn)任何接口,要對(duì)其進(jìn)行動(dòng)態(tài)代理只能使用CGLib小渊。
準(zhǔn)備依賴注入
在前面的分析中我們已經(jīng)了解到Bean 的依賴注入主要分為兩個(gè)步驟法褥,首先調(diào)用createBeanInstance()方法生成Bean 所包含的Java 對(duì)象實(shí)例。然后酬屉,調(diào)用populateBean()方法半等,對(duì)Bean 屬性的依賴注入進(jìn)行處理。
上面我們已經(jīng)分析了容器初始化生成Bean 所包含的Java 實(shí)例對(duì)象的過程呐萨,現(xiàn)在我們繼續(xù)分析生成對(duì)象后杀饵,Spring IOC 容器是如何將Bean 的屬性依賴關(guān)系注入Bean 實(shí)例對(duì)象中并設(shè)置好的,回到AbstractAutowireCapableBeanFactory 的populateBean()方法垛吗,對(duì)屬性依賴注入的代碼如下:
//將Bean 屬性設(shè)置到生成的實(shí)例對(duì)象上
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
} else {
return;
}
}
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
//獲取容器在解析Bean 定義資源時(shí)為BeanDefiniton 中設(shè)置的屬性值
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
if (pvs != null) {
//對(duì)屬性進(jìn)行注入
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
//解析并注入依賴屬性的過程
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs.isEmpty()) {
return;
}
//封裝屬性值
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
if (System.getSecurityManager() != null) {
if (bw instanceof BeanWrapperImpl) {
//設(shè)置安全上下文凹髓,JDK 安全機(jī)制
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
}
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
//屬性值已經(jīng)轉(zhuǎn)換
if (mpvs.isConverted()) {
try {
//為實(shí)例化對(duì)象設(shè)置屬性值
bw.setPropertyValues(mpvs);
return;
} catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
//獲取屬性值對(duì)象的原始類型值
original = mpvs.getPropertyValueList();
} else {
original = Arrays.asList(pvs.getPropertyValues());
}
//獲取用戶自定義的類型轉(zhuǎn)換
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
//創(chuàng)建一個(gè)Bean 定義屬性值解析器,將Bean 定義中的屬性值解析為Bean 實(shí)例對(duì)象的實(shí)際值
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
//為屬性的解析值創(chuàng)建一個(gè)拷貝怯屉,將拷貝的數(shù)據(jù)注入到實(shí)例對(duì)象中
List<PropertyValue> deepCopy = new ArrayList<>(original.size());
boolean resolveNecessary = false;
for (PropertyValue pv : original) {
//屬性值不需要轉(zhuǎn)換
if (pv.isConverted()) {
deepCopy.add(pv);
}
//屬性值需要轉(zhuǎn)換
else {
String propertyName = pv.getName();
//原始的屬性值蔚舀,即轉(zhuǎn)換之前的屬性值
Object originalValue = pv.getValue();
//轉(zhuǎn)換屬性值,例如將引用轉(zhuǎn)換為IOC 容器中實(shí)例化對(duì)象引用
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
//轉(zhuǎn)換之后的屬性值
Object convertedValue = resolvedValue;
//屬性值是否可以轉(zhuǎn)換
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
//使用用戶自定義的類型轉(zhuǎn)換器轉(zhuǎn)換屬性值
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
//存儲(chǔ)轉(zhuǎn)換后的屬性值锨络,避免每次屬性注入時(shí)的轉(zhuǎn)換工作
if (resolvedValue == originalValue) {
if (convertible) {
//設(shè)置屬性轉(zhuǎn)換之后的值
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
}
//屬性是可轉(zhuǎn)換的赌躺,且屬性原始值是字符串類型,且屬性的原始類型值不是
//動(dòng)態(tài)生成的字符串羡儿,且屬性的原始值不是集合或者數(shù)組類型
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
//重新封裝屬性的值
deepCopy.add(pv);
} else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) {
//標(biāo)記屬性值已經(jīng)轉(zhuǎn)換過
mpvs.setConverted();
}
//進(jìn)行屬性依賴注入
try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
} catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
分析上述代碼礼患,我們可以看出,對(duì)屬性的注入過程分以下兩種情況:
1)、屬性值類型不需要強(qiáng)制轉(zhuǎn)換時(shí)缅叠,不需要解析屬性值悄泥,直接準(zhǔn)備進(jìn)行依賴注入。
2)肤粱、屬性值需要進(jìn)行類型強(qiáng)制轉(zhuǎn)換時(shí)弹囚,如對(duì)其他對(duì)象的引用等,首先需要解析屬性值领曼,然后對(duì)解析后的屬性值進(jìn)行依賴注入鸥鹉。
對(duì)屬性值的解析是在BeanDefinitionValueResolver 類中的resolveValueIfNecessary()方法中進(jìn)行的,對(duì)屬性值的依賴注入是通過bw.setPropertyValues()方法實(shí)現(xiàn)的庶骄,在分析屬性值的依賴注入之前毁渗,我們先分析一下對(duì)屬性值的解析過程。
解析屬性注入規(guī)則
當(dāng)容器在對(duì)屬性進(jìn)行依賴注入時(shí)单刁,如果發(fā)現(xiàn)屬性值需要進(jìn)行類型轉(zhuǎn)換灸异,如屬性值是容器中另一個(gè)Bean實(shí)例對(duì)象的引用,則容器首先需要根據(jù)屬性值解析出所引用的對(duì)象幻碱,然后才能將該引用對(duì)象注入到目標(biāo)實(shí)例對(duì)象的屬性上去绎狭,對(duì)屬性進(jìn)行解析的由resolveValueIfNecessary()方法實(shí)現(xiàn),其源碼如下:
//解析屬性值褥傍,對(duì)注入類型進(jìn)行轉(zhuǎn)換
@Nullable
public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
//對(duì)引用類型的屬性進(jìn)行解析
if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
//調(diào)用引用類型屬性的解析方法
return resolveReference(argName, ref);
}
//對(duì)屬性值是引用容器中另一個(gè)Bean 名稱的解析
else if (value instanceof RuntimeBeanNameReference) {
String refName = ((RuntimeBeanNameReference) value).getBeanName();
refName = String.valueOf(doEvaluate(refName));
//從容器中獲取指定名稱的Bean
if (!this.beanFactory.containsBean(refName)) {
throw new BeanDefinitionStoreException(
"Invalid bean name '" + refName + "' in bean reference for " + argName);
}
return refName;
}
//對(duì)Bean 類型屬性的解析儡嘶,主要是Bean 中的內(nèi)部類
else if (value instanceof BeanDefinitionHolder) {
BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
} else if (value instanceof BeanDefinition) {
BeanDefinition bd = (BeanDefinition) value;
String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
ObjectUtils.getIdentityHexString(bd);
return resolveInnerBean(argName, innerBeanName, bd);
}
//對(duì)集合數(shù)組類型的屬性解析
else if (value instanceof ManagedArray) {
ManagedArray array = (ManagedArray) value;
//獲取數(shù)組的類型
Class<?> elementType = array.resolvedElementType;
if (elementType == null) {
//獲取數(shù)組元素的類型
String elementTypeName = array.getElementTypeName();
if (StringUtils.hasText(elementTypeName)) {
try {
//使用反射機(jī)制創(chuàng)建指定類型的對(duì)象
elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
array.resolvedElementType = elementType;
} catch (Throwable ex) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error resolving array type for " + argName, ex);
}
}
//沒有獲取到數(shù)組的類型,也沒有獲取到數(shù)組元素的類型
//則直接設(shè)置數(shù)組的類型為Object
else {
elementType = Object.class;
}
}
//創(chuàng)建指定類型的數(shù)組
return resolveManagedArray(argName, (List<?>) value, elementType);
}
//解析list 類型的屬性值
else if (value instanceof ManagedList) {
return resolveManagedList(argName, (List<?>) value);
}
//解析set 類型的屬性值
else if (value instanceof ManagedSet) {
return resolveManagedSet(argName, (Set<?>) value);
}
//解析map 類型的屬性值
else if (value instanceof ManagedMap) {
return resolveManagedMap(argName, (Map<?, ?>) value);
}
//解析props 類型的屬性值恍风,props 其實(shí)就是key 和value 均為字符串的map
else if (value instanceof ManagedProperties) {
Properties original = (Properties) value;
//創(chuàng)建一個(gè)拷貝蹦狂,用于作為解析后的返回值
Properties copy = new Properties();
original.forEach((propKey, propValue) -> {
if (propKey instanceof TypedStringValue) {
propKey = evaluate((TypedStringValue) propKey);
}
if (propValue instanceof TypedStringValue) {
propValue = evaluate((TypedStringValue) propValue);
}
if (propKey == null || propValue == null) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error converting Properties key/value pair for " + argName + ": resolved to null");
}
copy.put(propKey, propValue);
});
return copy;
}
//解析字符串類型的屬性值
else if (value instanceof TypedStringValue) {
TypedStringValue typedStringValue = (TypedStringValue) value;
Object valueObject = evaluate(typedStringValue);
try {
//獲取屬性的目標(biāo)類型
Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
if (resolvedTargetType != null) {
//對(duì)目標(biāo)類型的屬性進(jìn)行解析,遞歸調(diào)用
return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
}
//沒有獲取到屬性的目標(biāo)對(duì)象朋贬,則按Object 類型返回
else {
return valueObject;
}
} catch (Throwable ex) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error converting typed String value for " + argName, ex);
}
} else if (value instanceof NullBean) {
return null;
} else {
return evaluate(value);
}
}
//解析引用類型的屬性值
@Nullable
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
try {
Object bean;
//獲取引用的Bean 名稱
String refName = ref.getBeanName();
refName = String.valueOf(doEvaluate(refName));
//如果引用的對(duì)象在父類容器中凯楔,則從父類容器中獲取指定的引用對(duì)象
if (ref.isToParent()) {
if (this.beanFactory.getParentBeanFactory() == null) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Can't resolve reference to bean '" + refName +
"' in parent factory: no parent factory available");
}
bean = this.beanFactory.getParentBeanFactory().getBean(refName);
}
//從當(dāng)前的容器中獲取指定的引用Bean 對(duì)象,如果指定的Bean 沒有被實(shí)例化
//則會(huì)遞歸觸發(fā)引用Bean 的初始化和依賴注入
else {
bean = this.beanFactory.getBean(refName);
//將當(dāng)前實(shí)例化對(duì)象的依賴引用對(duì)象
this.beanFactory.registerDependentBean(refName, this.beanName);
}
if (bean instanceof NullBean) {
bean = null;
}
return bean;
} catch (BeansException ex) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
}
}
//解析array 類型的屬性
private Object resolveManagedArray(Object argName, List<?> ml, Class<?> elementType) {
//創(chuàng)建一個(gè)指定類型的數(shù)組锦募,用于存放和返回解析后的數(shù)組
Object resolved = Array.newInstance(elementType, ml.size());
for (int i = 0; i < ml.size(); i++) {
//遞歸解析array 的每一個(gè)元素摆屯,并將解析后的值設(shè)置到resolved 數(shù)組中,索引為i
Array.set(resolved, i,
resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i)));
}
return resolved;
}
通過上面的代碼分析糠亩,我們明白了Spring 是如何將引用類型虐骑,內(nèi)部類以及集合類型等屬性進(jìn)行解析的,屬性值解析完成后就可以進(jìn)行依賴注入了赎线,依賴注入的過程就是Bean 對(duì)象實(shí)例設(shè)置到它所依賴的Bean對(duì)象屬性上去廷没。而真正的依賴注入是通過bw.setPropertyValues()方法實(shí)現(xiàn)的,該方法也使用了委托模式垂寥, 在BeanWrapper 接口中至少定義了方法聲明颠黎, 依賴注入的具體實(shí)現(xiàn)交由其實(shí)現(xiàn)類BeanWrapperImpl 來完成另锋,下面我們就分析依BeanWrapperImpl 中賴注入相關(guān)的源碼。
注入賦值
BeanWrapperImpl 類主要是對(duì)容器中完成初始化的Bean 實(shí)例對(duì)象進(jìn)行屬性的依賴注入狭归,即把Bean對(duì)象設(shè)置到它所依賴的另一個(gè)Bean 的屬性中去夭坪。然而,BeanWrapperImpl 中的注入方法實(shí)際上由AbstractNestablePropertyAccessor 來實(shí)現(xiàn)的过椎,其相關(guān)源碼如下:
//實(shí)現(xiàn)屬性依賴注入功能
protected void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
if (tokens.keys != null) {
processKeyedProperty(tokens, pv);
} else {
processLocalProperty(tokens, pv);
}
}
//實(shí)現(xiàn)屬性依賴注入功能
@SuppressWarnings("unchecked")
private void processKeyedProperty(PropertyTokenHolder tokens, PropertyValue pv) {
//調(diào)用屬性的getter(readerMethod)方法台舱,獲取屬性的值
Object propValue = getPropertyHoldingValue(tokens);
PropertyHandler ph = getLocalPropertyHandler(tokens.actualName);
if (ph == null) {
throw new InvalidPropertyException(
getRootClass(), this.nestedPath + tokens.actualName, "No property handler found");
}
Assert.state(tokens.keys != null, "No token keys");
String lastKey = tokens.keys[tokens.keys.length - 1];
//注入array 類型的屬性值
if (propValue.getClass().isArray()) {
Class<?> requiredType = propValue.getClass().getComponentType();
int arrayIndex = Integer.parseInt(lastKey);
Object oldValue = null;
try {
if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
oldValue = Array.get(propValue, arrayIndex);
}
Object convertedValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
requiredType, ph.nested(tokens.keys.length));
//獲取集合類型屬性的長(zhǎng)度
int length = Array.getLength(propValue);
if (arrayIndex >= length && arrayIndex < this.autoGrowCollectionLimit) {
Class<?> componentType = propValue.getClass().getComponentType();
Object newArray = Array.newInstance(componentType, arrayIndex + 1);
System.arraycopy(propValue, 0, newArray, 0, length);
setPropertyValue(tokens.actualName, newArray);
//調(diào)用屬性的getter(readerMethod)方法,獲取屬性的值
propValue = getPropertyValue(tokens.actualName);
}
//將屬性的值賦值給數(shù)組中的元素
Array.set(propValue, arrayIndex, convertedValue);
} catch (IndexOutOfBoundsException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
"Invalid array index in property path '" + tokens.canonicalName + "'", ex);
}
}
//注入list 類型的屬性值
else if (propValue instanceof List) {
//獲取list 集合的類型
Class<?> requiredType = ph.getCollectionType(tokens.keys.length);
List<Object> list = (List<Object>) propValue;
//獲取list 集合的size
int index = Integer.parseInt(lastKey);
Object oldValue = null;
if (isExtractOldValueForEditor() && index < list.size()) {
oldValue = list.get(index);
}
//獲取list 解析后的屬性值
Object convertedValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
requiredType, ph.nested(tokens.keys.length));
int size = list.size();
//如果list 的長(zhǎng)度大于屬性值的長(zhǎng)度潭流,則多余的元素賦值為null
if (index >= size && index < this.autoGrowCollectionLimit) {
for (int i = size; i < index; i++) {
try {
list.add(null);
} catch (NullPointerException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
"Cannot set element with index " + index + " in List of size " +
size + ", accessed using property path '" + tokens.canonicalName +
"': List does not support filling up gaps with null elements");
}
}
list.add(convertedValue);
} else {
try {
//將值添加到list 中
list.set(index, convertedValue);
} catch (IndexOutOfBoundsException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
"Invalid list index in property path '" + tokens.canonicalName + "'", ex);
}
}
}
//注入map 類型的屬性值
else if (propValue instanceof Map) {
//獲取map 集合key 的類型
Class<?> mapKeyType = ph.getMapKeyType(tokens.keys.length);
//獲取map 集合value 的類型
Class<?> mapValueType = ph.getMapValueType(tokens.keys.length);
Map<Object, Object> map = (Map<Object, Object>) propValue;
TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
//解析map 類型屬性key 值
Object convertedMapKey = convertIfNecessary(null, null, lastKey, mapKeyType, typeDescriptor);
Object oldValue = null;
if (isExtractOldValueForEditor()) {
oldValue = map.get(convertedMapKey);
}
//解析map 類型屬性value 值
Object convertedMapValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
mapValueType, ph.nested(tokens.keys.length));
//將解析后的key 和value 值賦值給map 集合屬性
map.put(convertedMapKey, convertedMapValue);
} else {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
"Property referenced in indexed property path '" + tokens.canonicalName +
"' is neither an array nor a List nor a Map; returned value was [" + propValue + "]");
}
}
private Object getPropertyHoldingValue(PropertyTokenHolder tokens) {
Assert.state(tokens.keys != null, "No token keys");
PropertyTokenHolder getterTokens = new PropertyTokenHolder(tokens.actualName);
getterTokens.canonicalName = tokens.canonicalName;
getterTokens.keys = new String[tokens.keys.length - 1];
System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
Object propValue;
try {
//獲取屬性值
propValue = getPropertyValue(getterTokens);
} catch (NotReadablePropertyException ex) {
throw new NotWritablePropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
"Cannot access indexed value in property referenced " +
"in indexed property path '" + tokens.canonicalName + "'", ex);
}
if (propValue == null) {
if (isAutoGrowNestedPaths()) {
int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
propValue = setDefaultValue(getterTokens);
} else {
throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + tokens.canonicalName,
"Cannot access indexed value in property referenced " +
"in indexed property path '" + tokens.canonicalName + "': returned null");
}
}
return propValue;
}
通過對(duì)上面注入依賴代碼的分析,我們已經(jīng)明白了Spring IOC 容器是如何將屬性的值注入到Bean 實(shí)例對(duì)象中去的:
1)柜去、對(duì)于集合類型的屬性灰嫉,將其屬性值解析為目標(biāo)類型的集合后直接賦值給屬性。
2)嗓奢、對(duì)于非集合類型的屬性讼撒,大量使用了JDK 的反射機(jī)制,通過屬性的getter()方法獲取指定屬性注入以前的值股耽,同時(shí)調(diào)用屬性的setter()方法為屬性設(shè)置注入后的值根盒。看到這里相信很多人都明白了Spring的setter()注入原理物蝙。
至此Spring IOC 容器對(duì)Bean 定義資源文件的定位炎滞,載入、解析和依賴注入已經(jīng)全部分析完畢诬乞,現(xiàn)在Spring IOC 容器中管理了一系列靠依賴關(guān)系聯(lián)系起來的Bean册赛,程序不需要應(yīng)用自己手動(dòng)創(chuàng)建所需的對(duì)象,Spring IOC 容器會(huì)在我們使用的時(shí)候自動(dòng)為我們創(chuàng)建震嫉,并且為我們注入好相關(guān)的依賴森瘪,這就是Spring 核心功能的控制反轉(zhuǎn)和依賴注入的相關(guān)功能。