BeanDefinition 实例化过程
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;
}
BeanDefinition 实例化过程的更多相关文章
- Spring中bean的实例化过程
1.从缓存中.优先从一级缓存中拿,有则返回. 如果没有,则从二级缓存中获取,有则返回. 如果二级缓存中拿不到,则从三级缓存中拿,能拿到,则从三级缓存中删除,移到二级缓存. 如果三级缓存也没有,则返回n ...
- 聊聊spring之bean对象的实例化过程
在spring实例化 之前bean对象封装成 beanDefinition 对象 想了解详情的请参考上一篇文章 好了 我们聊聊 Bean 的实例化过程的几个重要角色 BeanDefinitionReg ...
- Spring 源码学习 - 单例bean的实例化过程
本文作者:geek,一个聪明好学的同事 1. 简介 开发中我们常用@Commpont,@Service,@Resource等注解或者配置xml去声明一个类,使其成为spring容器中的bean,以下我 ...
- Spring Ioc源码分析系列--Bean实例化过程(一)
Spring Ioc源码分析系列--Bean实例化过程(一) 前言 上一篇文章Spring Ioc源码分析系列--Ioc容器注册BeanPostProcessor后置处理器以及事件消息处理已经完成了对 ...
- Spring Ioc源码分析系列--Bean实例化过程(二)
Spring Ioc源码分析系列--Bean实例化过程(二) 前言 上篇文章Spring Ioc源码分析系列--Bean实例化过程(一)简单分析了getBean()方法,还记得分析了什么吗?不记得了才 ...
- Java继承--子类的实例化过程
一个对象的实例化过程: Person p = new Person(); 1,JVM会读取指定的路径下的Person.class文件,并加载进内存,并会先加载Person的父类(如果有直接的父类的情况 ...
- python--对象实例化过程
实例化过程: class luffy_stu: def __init__(self,name,age,sex): self.name = name self.age = age self.sex = ...
- 框架源码系列九:依赖注入DI、三种Bean配置方式的注册和实例化过程
一.依赖注入DI 学习目标1)搞清楚构造参数依赖注入的过程及类2)搞清楚注解方式的属性依赖注入在哪里完成的.学习思路1)思考我们手写时是如何做的2)读 spring 源码对比看它的实现3)Spring ...
- JVM总括四-类加载过程、双亲委派模型、对象实例化过程
JVM总括四-类加载过程.双亲委派模型.对象实例化过程 目录:JVM总括:目录 一. 类加载过程 类加载过程就是将.class文件转化为Class对象,类实例化的过程,(User user = new ...
随机推荐
- echarts图表自适应盒子的大小(盒子的大小是动态改变的),大到需要全屏展示
项目中用到了echarts,并且页面是自适应的,且页面中有一个[放大.缩小]功能,因此图表还需要根据盒子的大小来变化. 即:两个需求,如下: ① 图表根据窗口的大小自适应 ② 图表根据所在盒子的大小自 ...
- (转)Java8内存模型-永久代(PermGen)和元空间(Metaspace)
原文链接:https://www.cnblogs.com/paddix/p/5309550.html 一.JVM内存模型 根据jvm规范,jvm内存共分为虚拟机栈.堆.方法区.程序计算器.本地方法栈五 ...
- Linux编译阻塞型驱动遇到'TASK_NORMAL' undeclared (first use in this function)问题解决办法
http://blog.csdn.net/qq_16405157/article/details/49281793
- 怎么去掉zencart模板网址后面的zenid=数字这个东西
搜索引擎优化后第一次进入商店网址URL后面会出现zenid=XXXX 如:http://afish.cnblogs.com/zencart-zenid.html?zenid=tbisz675099db ...
- 个人学习SpringMVC总结
好记性不如烂笔头! 核心:前端控制器 处理器映射器(HandleMapping) 处理器适配器(HandleAdapter) 视图解析器 流程: 用户从浏览器发起请求,发送到服务器(Tomcat),由 ...
- Linux如何将pycharm添加到桌面
使用Ubuntu编辑器,在/usr/share/applications 目录下创建一个 Pycharm.destop的文件. sudo vim /usr/share/applications/Pyc ...
- docker资源隔离实现方式
默认情况下,一个容器没有资源限制,几乎可以使用宿主主机的所有资源.docker提供了控制内存.cpu.block io.但是实际上主要是namespace和cgroup控制资源的隔离. Docker的 ...
- python之路-笔录2[CSS&JS]
*** 目录 *** 1. 块级标签与行内标签 2. css常用清除样式 3. 两种清除浮动的方式 4. CSS学习 5. JS 学习 *** END *** 1. 块级标签与行内标签 常见的块级元素 ...
- 网页制作怎么加MP4,用HTML代码
<video src="movie.mp4" controls="controls"> 您的浏览器不支持 video 标签. </video& ...
- js 两个页面的传值 可以用父页面 子页面做
js 两个页面的传值 可以用父页面 子页面做 比如弹窗 将值传到子页面的时候 用get超长