BeanDefinition 實例化過程
AbstractBeanFactory#doGetBean
AbstractBeanFactory#
/**
* 根據 bean 名稱讀取 bean
*
* @param name bean 名稱
* @param requiredType 返回類型
* @param args 參數
* @param typeCheckOnly 只執行類型檢測
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
// 獲取規範名稱【將別名轉換爲規範名稱】
final String beanName = transformedBeanName(name);
Object bean;
// 1)嘗試從單例緩存中讀取【手動註冊的單例】
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
// 2)創建單例
else {
// 此多例 bean 是否在創建過程中
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 檢查 parentBeanFactory 中是否存在 Bean 定義
final BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
final String nameToLookup = originalBeanName(name);
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);
}
}
// 如果無需類型檢查,則標記指定的 bean 已經創建
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// 保證當前 bean 依賴的 bean 已經初始化
final String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (final String dep : dependsOn) {
// 是否有循環依賴
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 註冊依賴
registerDependentBean(dep, beanName);
try {
// 實例化依賴的 bean
getBean(dep);
}
catch (final NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// 1)創建 bean 單例
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
// AbstractAutowireCapableBeanFactory
return createBean(beanName, mbd, args);
}
catch (final BeansException ex) {
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 2)創建多例 bean 實例
else if (mbd.isPrototype()) {
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
// 3)創建指定作用域的 bean
else {
final String scopeName = mbd.getScope();
final Scope scope = scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
final Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (final 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 (final BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// 請求類型是否匹配目標實例
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
// 執行類型轉換
final T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (final TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
// 返回 bean
return (T) bean;
}
DefaultSingletonBeanRegistry#
/** 單例對象緩存: bean 名稱映射到 bean 實例 */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** 單例工廠緩存: bean 名稱映射到 ObjectFactory,用於處理循環依賴 */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** 早期單例對象緩存: bean 名稱映射到 bean 實例,用於處理循環依賴,此 bean 還未初始化 */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/** 已經註冊的單例 bean 名稱,按照註冊順序寫入 */
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
/** 當前正在創建的 bean 的名稱,用於處理循環依賴 */
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
@Override
@Nullable
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
/**
* 根據 bean 的名稱獲取單例
*/
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 此單例已經實例化
Object singletonObject = singletonObjects.get(beanName);
// 當前 beanName 在創建過程中
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (singletonObjects) {
// 從 earlySingletonObjects 中讀取 bean
singletonObject = earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
// 如果允許循環引用,則從 singletonFactories 中讀取 ObjectFactory 並創建實例
final ObjectFactory<?> singletonFactory = singletonFactories.get(beanName);
if (singletonFactory != null) {
// 將新建的單例加入到 earlySingletonObjects 中
singletonObject = singletonFactory.getObject();
earlySingletonObjects.put(beanName, singletonObject);
singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (singletonObjects) {
Object singletonObject = singletonObjects.get(beanName);
if (singletonObject == null) {
if (singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
// 1)將 beanName 寫入 singletonsCurrentlyInCreation
beforeSingletonCreation(beanName);
boolean newSingleton = false;
final boolean recordSuppressedExceptions = suppressedExceptions == null;
if (recordSuppressedExceptions) {
suppressedExceptions = new LinkedHashSet<>();
}
try {
// 2)創建實例
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (final IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (final BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (final Exception suppressedException : suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
suppressedExceptions = null;
}
// 將 beanName 從 singletonsCurrentlyInCreation 中移除
afterSingletonCreation(beanName);
}
if (newSingleton) {
/**
* 將單例寫入 singletonObjects 和 registeredSingletons,
* 並從爲解決循環依賴而使用的 earlySingletonObjects 和 singletonFactories 中移除
*/
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
/**
* 默認創建 bean 的抽象 Bean 工廠,具有 RootBeanDefinition 指定的所有功能。
* 提供 bean 創建、屬性填充、自動注入、初始化、處理運行時 bean 引用、調用初始化方法等。
* 支持基於構造函數的注入、基於屬性名稱的注入、基於屬性類型的注入。
*/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
/**
* 創建 Bean 的核心方法
* 1)實例化
* 2)依賴注入屬性
* 3)執行 bean 的後處理
*/
@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;
// 1)保證 bean 類型已經完成解析
final Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// 2)準備方法覆蓋
try {
mbdToUse.prepareMethodOverrides();
}
catch (final BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
final Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
// 如果創建成功,則返回
if (bean != null) {
return bean;
}
}
catch (final Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
// 創建 bean 實例
final Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (final Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
/**
* 創建 Bean 實例
*/
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
// 如果是單例
if (mbd.isSingleton()) {
// 如果是未完成 FactoryBean 實例
instanceWrapper = factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 創建 BeanWrapper
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
final Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
// 寫入 bean Class
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (final Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// 急切地緩存未創建完成的單例,以解決循環依賴問題
final boolean earlySingletonExposure = mbd.isSingleton() && allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName);
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 將此實例加入 singletonFactories
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// 初始化 bean 實例
Object exposedObject = bean;
try {
// 依賴注入屬性
populateBean(beanName, mbd, instanceWrapper);
// 觸發 bean 實例的後處理
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (final 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) {
final Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
final String[] dependentBeans = getDependentBeans(beanName);
final Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (final 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 " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (final BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
/**
* 使用指定的實例化策略創建 bean 實例:
* 工廠方法、有參構造函數、無參構造函數
*/
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 決定 bean 類型
final Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 目標類型不是 public && 不允許通過非 public 方法創建實例,則拋出 BeanCreationException 異常
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());
}
// 1)嘗試通過實例生成器創建 bean
final Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
// 2)嘗試通過工廠方法創建 bean
if (mbd.getFactoryMethodName() != null) {
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);
}
}
// 3)嘗試通過自動注入的構造函數創建 bean 實例
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// 4)嘗試通過首選構造函數創建
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// 5)使用無參構造函數創建實例
return instantiateBean(beanName, mbd);
}
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 {
// 使用指定的實例化策略創建 bean 實例,一般通過 BeanUtils.instantiateClass(constructorToUse) 方法創建
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
final BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (final Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (final BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
final MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
/**
* 獲取對指定bean的早期訪問的引用,主要用於解決循環依賴
*/
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (final BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
final SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
/**
* 使用從 BeanDefinition 中讀取的屬性值填充 bean 屬性
*/
@SuppressWarnings("deprecation") // for postProcessPropertyValues
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 {
// Skip property population phase for null instance.
return;
}
}
/**
* 給 InstantiationAwareBeanPostProcessor 修改依賴注入流程的機會,
* 可以實現屬性注入。
*/
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (final BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
final InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
// 如果已經完成了字段的注入,則直接返回
if (!continueWithPropertyPopulation) {
return;
}
// 讀取 PropertyValues
PropertyValues pvs = mbd.hasPropertyValues() ? mbd.getPropertyValues() : null;
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
final MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
final boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
final boolean needsDepCheck = mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE;
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (final BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
final 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);
}
// 執行剩餘屬性的依賴注入
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
// 沒有屬性需要執行依賴注入,直接返回
if (pvs.isEmpty()) {
return;
}
if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
bw.setPropertyValues(mpvs);
return;
}
catch (final BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
original = mpvs.getPropertyValueList();
}
else {
// 讀取待注入的屬性列表
original = Arrays.asList(pvs.getPropertyValues());
}
// 讀取自定義類型轉換器
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
// BeanDefinition 值解析器
final BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// 創建一個深度拷貝,解析值引用
final List<PropertyValue> deepCopy = new ArrayList<>(original.size());
boolean resolveNecessary = false;
for (final PropertyValue pv : original) {
// 已經完成轉換
if (pv.isConverted()) {
deepCopy.add(pv);
}
else {
// 讀取屬性名稱
final String propertyName = pv.getName();
// 讀取元素值
final Object originalValue = pv.getValue();
// 解析值
final Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
final boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
// 如果需要轉換,則執行類型轉換
if (convertible) {
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// 寫入 BeanDefinition 中避免再次轉換
if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
}
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
}
else {
// 創建 PropertyValue 並加入 deepCopy
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) {
mpvs.setConverted();
}
// 將深度拷貝對象注入 bean 的屬性中
try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (final BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
AbstractPropertyAccessor#
@Override
public void setPropertyValues(PropertyValues pvs) throws BeansException {
setPropertyValues(pvs, false, false);
}
@Override
public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown) throws BeansException {
setPropertyValues(pvs, ignoreUnknown, false);
}
@Override
public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid)
throws BeansException {
List<PropertyAccessException> propertyAccessExceptions = null;
final List<PropertyValue> propertyValues = pvs instanceof MutablePropertyValues? ((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues());
for (final PropertyValue pv : propertyValues) {
try {
// 設置的屬性
setPropertyValue(pv);
} catch (final NotWritablePropertyException ex) {
if (!ignoreUnknown) {
throw ex;
}
// Otherwise, just ignore it and continue...
} catch (final NullValueInNestedPathException ex) {
if (!ignoreInvalid) {
throw ex;
}
// Otherwise, just ignore it and continue...
} catch (final PropertyAccessException ex) {
if (propertyAccessExceptions == null) {
propertyAccessExceptions = new ArrayList<>();
}
propertyAccessExceptions.add(ex);
}
}
// If we encountered individual exceptions, throw the composite exception.
if (propertyAccessExceptions != null) {
final PropertyAccessException[] paeArray = propertyAccessExceptions.toArray(new PropertyAccessException[0]);
throw new PropertyBatchUpdateException(paeArray);
}
}
AbstractNestablePropertyAccessor#
@Override
public void setPropertyValue(PropertyValue pv) throws BeansException {
PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens;
// 1)屬性名稱爲解析
if (tokens == null) {
// 讀取屬性名稱
final String propertyName = pv.getName();
AbstractNestablePropertyAccessor nestedPa;
try {
// 讀取最內層的屬性訪問器,如果存在嵌套屬性
nestedPa = getPropertyAccessorForPropertyPath(propertyName);
}
catch (final NotReadablePropertyException ex) {
throw new NotWritablePropertyException(getRootClass(), nestedPath + propertyName,
"Nested property in path '" + propertyName + "' does not exist", ex);
}
// 讀取最內層的屬性名稱
tokens = getPropertyNameTokens(getFinalPath(nestedPa, propertyName));
if (nestedPa == this) {
// 無嵌套屬性
pv.getOriginalPropertyValue().resolvedTokens = tokens;
}
// 通過屬性訪問器設置屬性值
nestedPa.setPropertyValue(tokens, pv);
}
// 2)屬性名稱已解析
else {
setPropertyValue(tokens, pv);
}
}
/**
* 遞歸導航以返回最內層屬性的屬性訪問器
*/
@SuppressWarnings("unchecked") // avoid nested generic
protected AbstractNestablePropertyAccessor getPropertyAccessorForPropertyPath(String propertyPath) {
final int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);
// Handle nested properties recursively.
if (pos > -1) {
final String nestedProperty = propertyPath.substring(0, pos);
final String nestedPath = propertyPath.substring(pos + 1);
final AbstractNestablePropertyAccessor nestedPa = getNestedPropertyAccessor(nestedProperty);
return nestedPa.getPropertyAccessorForPropertyPath(nestedPath);
}
else {
return this;
}
}
/**
* 將屬性名稱解析爲 token
*/
private PropertyTokenHolder getPropertyNameTokens(String propertyName) {
String actualName = null;
// 內嵌的屬性列表
final List<String> keys = new ArrayList<>(2);
int searchIndex = 0;
// user['address'][name]
while (searchIndex != -1) {
// 讀取 [ 的起始索引
final int keyStart = propertyName.indexOf(PROPERTY_KEY_PREFIX, searchIndex);
searchIndex = -1;
if (keyStart != -1) {
// 讀取緊跟 ] 的索引
final int keyEnd = propertyName.indexOf(PROPERTY_KEY_SUFFIX, keyStart + PROPERTY_KEY_PREFIX.length());
if (keyEnd != -1) {
// 讀取第一個屬性名稱
if (actualName == null) {
actualName = propertyName.substring(0, keyStart);
}
// 讀取 key,如果 key 被 ' 或 " 包含,則將符號去除
String key = propertyName.substring(keyStart + PROPERTY_KEY_PREFIX.length(), keyEnd);
if (key.length() > 1 && key.startsWith("'") && key.endsWith("'") ||
key.startsWith("\"") && key.endsWith("\"")) {
key = key.substring(1, key.length() - 1);
}
// 加入 key
keys.add(key);
// 更新 searchIndex
searchIndex = keyEnd + PROPERTY_KEY_SUFFIX.length();
}
}
}
// 寫入屬性名稱
final PropertyTokenHolder tokens = new PropertyTokenHolder(actualName != null ? actualName : propertyName);
// 如果存在分層屬性
if (!keys.isEmpty()) {
// 寫入規範名稱 [address][name]
tokens.canonicalName += PROPERTY_KEY_PREFIX +
StringUtils.collectionToDelimitedString(keys, PROPERTY_KEY_SUFFIX + PROPERTY_KEY_PREFIX) +
PROPERTY_KEY_SUFFIX;
tokens.keys = StringUtils.toStringArray(keys);
}
return tokens;
}
protected void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
if (tokens.keys != null) {
processKeyedProperty(tokens, pv);
}
else {
// 設置本地屬性
processLocalProperty(tokens, pv);
}
}
private void processLocalProperty(PropertyTokenHolder tokens, PropertyValue pv) {
// 獲取基於屬性描述符的 BeanPropertyHandler
final PropertyHandler ph = getLocalPropertyHandler(tokens.actualName);
if (ph == null || !ph.isWritable()) {
if (pv.isOptional()) {
if (logger.isDebugEnabled()) {
logger.debug("Ignoring optional value for property '" + tokens.actualName +
"' - property not found on bean class [" + getRootClass().getName() + "]");
}
return;
}
else {
throw createNotWritablePropertyException(tokens.canonicalName);
}
}
// 1)舊值
Object oldValue = null;
try {
// 2)讀取原始值
final Object originalValue = pv.getValue();
Object valueToApply = originalValue;
if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
if (pv.isConverted()) {
valueToApply = pv.getConvertedValue();
}
else {
if (isExtractOldValueForEditor() && ph.isReadable()) {
try {
oldValue = ph.getValue();
}
catch (Exception ex) {
if (ex instanceof PrivilegedActionException) {
ex = ((PrivilegedActionException) ex).getException();
}
if (logger.isDebugEnabled()) {
logger.debug("Could not read previous value of property '" +
nestedPath + tokens.canonicalName + "'", ex);
}
}
}
// 如果必要,則執行轉換
valueToApply = convertForProperty(
tokens.canonicalName, oldValue, originalValue, ph.toTypeDescriptor());
}
// 寫入轉換標識
pv.getOriginalPropertyValue().conversionNecessary = valueToApply != originalValue;
}
// 通過 PropertyHandler 寫入值
ph.setValue(valueToApply);
}
catch (final TypeMismatchException ex) {
throw ex;
}
catch (final InvocationTargetException ex) {
final PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(
getRootInstance(), nestedPath + tokens.canonicalName, oldValue, pv.getValue());
if (ex.getTargetException() instanceof ClassCastException) {
throw new TypeMismatchException(propertyChangeEvent, ph.getPropertyType(), ex.getTargetException());
}
else {
Throwable cause = ex.getTargetException();
if (cause instanceof UndeclaredThrowableException) {
// May happen e.g. with Groovy-generated methods
cause = cause.getCause();
}
throw new MethodInvocationException(propertyChangeEvent, cause);
}
}
catch (final Exception ex) {
final PropertyChangeEvent pce = new PropertyChangeEvent(
getRootInstance(), nestedPath + tokens.canonicalName, oldValue, pv.getValue());
throw new MethodInvocationException(pce, ex);
}
}
BeanWrapperImpl#
/**
* 獲取 BeanPropertyHandler
*/
@Override
@Nullable
protected BeanPropertyHandler getLocalPropertyHandler(String propertyName) {
final PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(propertyName);
return pd != null ? new BeanPropertyHandler(pd) : null;
}
private class BeanPropertyHandler extends PropertyHandler {
/**
* 屬性描述符
*/
private final PropertyDescriptor pd;
public BeanPropertyHandler(PropertyDescriptor pd) {
super(pd.getPropertyType(), pd.getReadMethod() != null, pd.getWriteMethod() != null);
this.pd = pd;
}
@Override
public ResolvableType getResolvableType() {
return ResolvableType.forMethodReturnType(pd.getReadMethod());
}
@Override
public TypeDescriptor toTypeDescriptor() {
return new TypeDescriptor(property(pd));
}
@Override
@Nullable
public TypeDescriptor nested(int level) {
return TypeDescriptor.nested(property(pd), level);
}
/**
* 讀取值
*/
@Override
@Nullable
public Object getValue() throws Exception {
// 獲取讀方法
final Method readMethod = pd.getReadMethod();
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(readMethod);
return null;
});
try {
return AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
readMethod.invoke(getWrappedInstance(), (Object[]) null), acc);
}
catch (final PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 讀取值
ReflectionUtils.makeAccessible(readMethod);
return readMethod.invoke(getWrappedInstance(), (Object[]) null);
}
}
/**
* 寫入值
*/
@Override
public void setValue(final @Nullable Object value) throws Exception {
// 獲取寫方法
final Method writeMethod = pd instanceof GenericTypeAwarePropertyDescriptor ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() :
pd.getWriteMethod();
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(writeMethod);
return null;
});
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
writeMethod.invoke(getWrappedInstance(), value), acc);
}
catch (final PrivilegedActionException ex) {
throw ex.getException();
}
}
else {
// 寫入值
ReflectionUtils.makeAccessible(writeMethod);
writeMethod.invoke(getWrappedInstance(), value);
}
}
}
AbstractAutowireCapableBeanFactory#
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// 1)執行 Aware 注入
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 2)執行 BeanPostProcessor 的 postProcessBeforeInitialization 處理方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 3)執行初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (final Throwable ex) {
throw new BeanCreationException(
mbd != null ? mbd.getResourceDescription() : null,
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 4)執行 BeanPostProcessor 的 postProcessAfterInitialization 處理方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
// 返回創建完畢的 bean
return wrappedBean;
}
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
// 注入 BeanName
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
// 注入 BeanClassLoader
if (bean instanceof BeanClassLoaderAware) {
final ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
// 注入 BeanFactory
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
/**
* 執行 BeanPostProcessor#postProcessBeforeInitialization
*/
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (final BeanPostProcessor processor : getBeanPostProcessors()) {
final Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
/**
* 執行 bean 實例最後一步處理
*/
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (final BeanPostProcessor processor : getBeanPostProcessors()) {
final Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
AbstractBeanFactory#
/**
* 返回實例本身或其創建的對象 FactoryBean
*/
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// bean 名稱是否以 & 開頭
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
}
/**
* 如果不是 FactoryBean 則直接返回此對象
*/
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
Object object = null;
if (mbd == null) {
// 獲取緩存的由 FactoryBean 創建的實例
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
final FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
final boolean synthetic = mbd != null && mbd.isSynthetic();
// 從 FactoryBean 中獲取 Bean 實例
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}