博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring源码解析(八)——实例创建(下)
阅读量:5729 次
发布时间:2019-06-18

本文共 22568 字,大约阅读时间需要 75 分钟。

hot3.png

前言

    来到实例创建的最后一节,前面已经将一个实例通过不同方式(工厂方法、构造器注入、默认构造器)给创建出来了,下面我们要对创建出来的实例进行一些“加工”处理。

 

源码解读

    回顾下之前的代码,经过实例化之后,我们可以通过 BeanWrapper.getWrappedInstance 获取创建好的实例对象。

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)            throws BeanCreationException {        ......        final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);        Class
beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); mbd.resolvedTargetType = beanType; Object exposedObject = bean; try { // 属性填充 populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { // 初始化逻辑 exposedObject = initializeBean(beanName, exposedObject, mbd); } }......// 省略 catch ...... // 注册bean(这里的bean仅是未进行属性填充的bean) try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }

    这节将对方法 populateBeaninitializeBeanregisterDisposableBeanIfNecessary 展开分析。

 

populateBean

    从命名上,就可以看出这个方法是对实例的“填充”处理。

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {        // 获取bean的属性值        PropertyValues pvs = mbd.getPropertyValues();        if (bw == null) {            if (!pvs.isEmpty()) {                .....// 抛异常,无法为一个空实例填充            } else {                // 跳过空实例                return;            }        }        // 给任何 InstantiationAwareBeanPostProcessor提供在设置属性之前修改 bean状态的机会        // 例如:用来支持字段注入的风格        boolean continueWithPropertyPopulation = true;        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {            // 遍历所有的 InstantiationAwareBeanPostProcessor            for (BeanPostProcessor bp : getBeanPostProcessors()) {                if (bp instanceof InstantiationAwareBeanPostProcessor) {                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;                    // 生命周期:执行 postProcessAfterInstantiation                    // 该方法返回false会终止之后的填充                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {                        continueWithPropertyPopulation = false;                        break;                    }                }            }        }        // postProcessAfterInstantiation 返回false        if (!continueWithPropertyPopulation) {            return;        }        // 判断实例自动装配方式:byName、byType        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||                mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {            // 拷贝一份属性信息(因为解析自动注入会对 newPvs修改)            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             pvs = newPvs;        }        // 是否注册有 InstantiationAwareBeanPostProcessor        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();        // 需要依赖检查        boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);        if (hasInstAwareBpps || needsDepCheck) {            PropertyDescriptor[] filteredPds =                         filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);            if (hasInstAwareBpps) {                // 遍历所有 InstantiationAwareBeanPostProcessor                for (BeanPostProcessor bp : getBeanPostProcessors()) {                    if (bp instanceof InstantiationAwareBeanPostProcessor) {                        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;                        // 生命周期:执行 postProcessPropertyValues                        pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);                        if (pvs == null) {                            return;                        }                    }                }            }            if (needsDepCheck) {                // 依赖检查,以确定所有暴露的属性都已设置                checkDependencies(beanName, mbd, filteredPds, pvs);            }        }        // 调用 BeanWrapper.setPropertyValues,将所有属性填充        applyPropertyValues(beanName, mbd, bw, pvs);    }

    属性填充整个流程分为(除生命周期相关接口外):自动装配逻辑常规的属性填充。先来看看自动装配的逻辑吧,分为“名称”和“类型”自动注入。

protected void autowireByName(            String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {        // 获取实例中需要依赖注入的属性名称        String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);        for (String propertyName : propertyNames) {            // 容器中包含此属性的定义            if (containsBean(propertyName)) {                // 获取,如果还未创建则创建                Object bean = getBean(propertyName);                // 将 bean与属性进行关联绑定                pvs.add(propertyName, bean);                // 注册依赖关系:key-propertyName,value-所有依赖该属性的 beanName                registerDependentBean(propertyName, beanName);                                ....// 省略日志            } else {                ....// 省略日志            }        }    }
protected void autowireByType(            String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {        TypeConverter converter = getCustomTypeConverter();        if (converter == null) {            converter = bw;        }        Set
autowiredBeanNames = new LinkedHashSet
(4); // 寻找实例中需要依赖注入的属性 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { try { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); // 不会为类型为 Object的属性进行自动装配: if (Object.class != pd.getPropertyType()) { // 探测指定属性的 set方法 MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); // 类型匹配 PriorityOrdered后处理器,不允许初始化 boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass()); DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager); // 根据属性类型从容器中获取匹配的 bean,并把解析到的属性名称存储到 autowiredBeanNames中 Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); if (autowiredArgument != null) { pvs.add(propertyName, autowiredArgument); } // 注册依赖关系:key-autowiredBeanName,value-所有依赖该属性的 beanName for (String autowiredBeanName : autowiredBeanNames) { registerDependentBean(autowiredBeanName, beanName); ...// 省略日志 } autowiredBeanNames.clear(); } } catch (BeansException ex) { throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); } } }

    两种方式公共的逻辑:遍历需要注入的属性——>从容器中找到符合条件的实例——>将实例与属性绑定——>注册依赖关系。

    通过名称注入的逻辑简单点,通过 getBean 方法获取即可;

    通过类型注入的逻辑稍微复杂点,主要集中在 resolveDependency 方法:

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory        implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {    @Override    public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,                     Set
autowiredBeanNames, TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(getParameterNameDiscoverer()); // getDependencyType会调用 Field.getGenericType获取成员变量声明类型(包含泛型类型) // java.util.Optional类型 if (javaUtilOptionalClass == descriptor.getDependencyType()) { // 将 doResolveDependency返回包装成 Optional return new OptionalDependencyFactory().createOptionalDependency(descriptor, requestingBeanName); } // ObjectFactory或 ObjectProvider类型 else if (ObjectFactory.class == descriptor.getDependencyType() || ObjectProvider.class == descriptor.getDependencyType()) { return new DependencyObjectProvider(descriptor, requestingBeanName); } // javax.inject.Provider类型 else if (javaxInjectProviderClass == descriptor.getDependencyType()) { return new Jsr330ProviderFactory().createDependencyProvider(descriptor, requestingBeanName); } else { // ContextAnnotationAutowireCandidateResolver实现了 getLazyResolutionProxyIfNecessary // 对于被 @Lazy标识的成员,通过代理支持延迟加载 Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary( descriptor, requestingBeanName); if (result == null) { // 非延迟加载处理逻辑 result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); } return result; } } public Object doResolveDependency(DependencyDescriptor descriptor, String beanName, Set
autowiredBeanNames, TypeConverter typeConverter) throws BeansException { // 记录当前注入点 InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { // 捷径:由 ShortcutDependencyDescriptor实现 // 调用 getBean(String name, Class
requiredType)直接获取 Object shortcut = descriptor.resolveShortcut(this); if (shortcut != null) { return shortcut; } Class
type = descriptor.getDependencyType(); // QualifierAnnotationAutowireCandidateResolver:支持 @Value Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { if (value instanceof String) { // 解析:通过 StringValueResolver.resolveStringValue String strVal = resolveEmbeddedValue((String) value); BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); // 评估:通过 BeanExpressionResolver.evaluate value = evaluateBeanDefinitionString(strVal, bd); } // 进行类型转换 TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return (descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); } // 数组类型的解析,会将所有满足条件的候选者填充 autowiredBeanNames Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); if (multipleBeans != null) { return multipleBeans; } // 根据属性类型在容器中找到所有的匹配 bean,key-的beanName,value=对应的bean Map
matchingBeans = findAutowireCandidates(beanName, type, descriptor); // 未找到匹配类型的 bean if (matchingBeans.isEmpty()) { // 如果 autowired的 require属性为 true(默认),但匹配为空,抛异常 if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } return null; } String autowiredBeanName; Object instanceCandidate; // 多个匹配者的处理 if (matchingBeans.size() > 1) { // 通过
配置的 primary属性来判断,多个同类型 bean同时配置 primary会抛异常 // 如果上面没结果,则通过 @Priority注解来筛选 // 依旧没有结果,通过候选名称与成员定义的 beanName/别名匹配 autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); if (autowiredBeanName == null) { if (isRequired(descriptor) || !indicatesMultipleBeans(type)) { // 抛 NoUniqueBeanDefinitionException异常 return descriptor.resolveNotUnique(type, matchingBeans); } else { // 如果依赖是可选的集合,就返回一个空 return null; } } instanceCandidate = matchingBeans.get(autowiredBeanName); } // 匹配的恰好有一个 else { Map.Entry
entry = matchingBeans.entrySet().iterator().next(); autowiredBeanName = entry.getKey(); instanceCandidate = entry.getValue(); } // 用于上层的注册操作 if (autowiredBeanNames != null) { // 非数组类型只会添加一个 autowiredBeanNames.add(autowiredBeanName); } return (instanceCandidate instanceof Class ? descriptor.resolveCandidate(autowiredBeanName, type, this) : instanceCandidate); } finally { // 与开头的 ConstructorResolver.setCurrentInjectionPoint(descriptor)呼应 ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } }}

   经过上面的代码,就可以获取到属性和值对应关系的全集——PropertyValues pvs,接下来,我们看下 applyPropertyValues 如何将值赋给对应的属性。

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {        if (pvs == null || pvs.isEmpty()) {            return;        }        MutablePropertyValues mpvs = null;        List
original; if (System.getSecurityManager() != null) { if (bw instanceof BeanWrapperImpl) { ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); } } if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; // 已经转换成对应类型 MutablePropertyValues,直接设置到实例 if (mpvs.isConverted()) { try { bw.setPropertyValues(mpvs); return; } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } original = mpvs.getPropertyValueList(); } else { // 非 MutablePropertyValues,直接使用原始属性获取方法 original = Arrays.asList(pvs.getPropertyValues()); } // 用于类型转换 TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); List
deepCopy = new ArrayList
(original.size()); boolean resolveNecessary = false; // 遍历属性,将属性转换成对应类属性的类型 for (PropertyValue pv : original) { if (pv.isConverted()) { deepCopy.add(pv); } else { String propertyName = pv.getName(); Object originalValue = pv.getValue(); Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue); Object convertedValue = resolvedValue; // 属性可写,且不是指示索引(person.addresses[0])或嵌套属性(foo.bar) 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 { resolveNecessary = true; deepCopy.add(new PropertyValue(pv, convertedValue)); } } } if (mpvs != null && !resolveNecessary) { mpvs.setConverted(); } try { // 赋值. bw.setPropertyValues(new MutablePropertyValues(deepCopy)); } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } }

    到这里为止,实例的成员变量赋值工作就结束了。

 

initializeBean

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {        if (System.getSecurityManager() != null) {            AccessController.doPrivileged(new PrivilegedAction() {                @Override                public Object run() {                    invokeAwareMethods(beanName, bean);                    return null;                }            }, getAccessControlContext());        } else {            // BeanNameAware、BeanClassLoaderAware、BeanFactoryAware            invokeAwareMethods(beanName, bean);        }        Object wrappedBean = bean;        if (mbd == null || !mbd.isSynthetic()) {            // 生命周期:BeanPostProcessor.postProcessBeforeInitialization            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);        }        try {            // 调用
invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || !mbd.isSynthetic()) { // 生命周期:BeanPostProcessor.postProcessAfterInitialization wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }

    涉及到几个 Aware 接口的执行,之后就是两个生命周期接口的调用(postProcessBeforeInitialization postProcessAfterInitialization),中间夹带着 invokeInitMethods

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)            throws Throwable {        boolean isInitializingBean = (bean instanceof InitializingBean);        if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {            if (logger.isDebugEnabled()) {                logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");            }            if (System.getSecurityManager() != null) {                try {                    AccessController.doPrivileged(new PrivilegedExceptionAction() {                        @Override                        public Object run() throws Exception {                            ((InitializingBean) bean).afterPropertiesSet();                            return null;                        }                    }, getAccessControlContext());                } catch (PrivilegedActionException pae) {                    throw pae.getException();                }            } else {                // 生命周期:InitializingBean.afterPropertiesSet                ((InitializingBean) bean).afterPropertiesSet();            }        }        if (mbd != null) {            String initMethodName = mbd.getInitMethodName();            if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&                    !mbd.isExternallyManagedInitMethod(initMethodName)) {                //通过反射找到 
并执行 invokeCustomInitMethod(beanName, bean, mbd); } } }

 

registerDisposableBeanIfNecessary

    这里注册是 beanName 和销毁相关的映射关系,比如我们容器需要销毁指定的实例,如果实例实现了DisposableBean、指定了<destroy-method>等等,我们会将这些都封装成 DisposableBeanAdapter,然后在销毁时通过映射关系找到并调用其 destroy 方法。

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {        AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);        // 非 Prototype且需要销毁处理(满足任意条件)        // 条件1:实现 DisposableBean/AutoCloseable(不存在使用 Closeable)        // 条件2:没配置 
,默认是 close和 shutdown方法 // 条件3:配置了
,则使用配置的 // 条件3:以上都不满足,可以通过注册 DestructionAwareBeanPostProcessor,且 requiresDestruction返回 true if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) { if (mbd.isSingleton()) { // 注册一个 DisposableBean实现,该实现为给定的 bean执行所有销毁工作: // DestructionAwareBeanPostProcessors,DisposableBean接口,自定义销毁方法 // 注册单例 beanName和 DisposableBeanAdapter映射关系 registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } else { // 在各 Scope下存储 beanName和 DisposableBeanAdapter映射关系 Scope scope = this.scopes.get(mbd.getScope()); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'"); } scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } } }

    这一步维护的销毁映射关系,会在合适的时机被调用。以单例为例,会在容器销毁时被调用。

public void destroySingleton(String beanName) {        // 移除一个已注册的单例        removeSingleton(beanName);        // 取出对应的 DisposableBean        DisposableBean disposableBean;        synchronized (this.disposableBeans) {            disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);        }        // 调用相关 bean、自身、以及包含的成员 bean        // DisposableBean.destroy        destroyBean(beanName, disposableBean);    }

 

总结

    目前为之,基本就把容器启动——>实例创建这条主线给解析完毕了,期间涉及到了许多 Bean 相关的生命周期接口,现整理如下:

bean生命周期图

转载于:https://my.oschina.net/marvelcode/blog/1835378

你可能感兴趣的文章
js scroll事件
查看>>
day08 文件操作
查看>>
最长递增子序列 动态规划
查看>>
「小程序JAVA实战」微信小程序工程结构了解(五)
查看>>
使用列表
查看>>
Edge browser hosts file
查看>>
原生CSS设置网站主题色—CSS变量赋值
查看>>
概率dp - UVA 11021 Tribles
查看>>
webpack 4.0 中 clean-webpack-plugin 的使用
查看>>
数据库神器:Navicat Premium
查看>>
WPF
查看>>
Best website for Photogrammetry
查看>>
中文词频统计
查看>>
POJ 2236 Wireless Network (并查集)
查看>>
python分类
查看>>
linux 中常见的压缩和解压缩的命令
查看>>
GitBlit (1)-- 在linux 安装 GitBlit 并运行
查看>>
Windows与Linux之间的文件自动同步
查看>>
topcoder srm 714 div1
查看>>
20160215
查看>>