spring源码学习(五)Bean的加载(上)
2017-09-01 15:09
513 查看
这篇文章主要介绍spring的bean的加载。
这是doGetBean的方法,也是加载bean的方法。
这段代码非常长,bean对象加载的过程就是上面这个代码段。先把转换beanName,然后看看有没有缓存,若有缓存则实例化bean,若没有则看看是非是原型模式依赖的情况,检查parentBeanFactory,把gernericBeanDefinition转换成RootBeanFactory,寻找依赖,针对不同的scope创建bean,转换类型。
getSingleton函数体
检查缓存中是否存在实例,如果为空,则从earlySingletonObjects里面获取,如果还获取不到,再尝试从SingletonFactories里面获取beanName对应的ObjectFactory,调用这个ObjectFactory来创建bean,然后放到earlySingletonObjects里面去,然后从SingletonFactories把这个beanName去掉。
getObjectForBeanInstance函数
对factoryBean进行验证,对bean进行转换,将factory解析bean的工作交给getObjectFromFactoryBean完成。
在这个方法体里主要保证返回的bean如果是单例就保证全局唯一性,不用重复创建单例,可以使用缓存来提高性能,以便下获取。
doGetObjectFromFactoryBean方法
当bean是FactoryBean类型时,提取Bean是得到FactoryBean中的getObject方法中放回的bean。
我们拿到factory.getObject(),然后程序回到getObjectFromFactoryBean方法中,没有直接返回,而是执行了postProcessObjectFromFactoryBean(object, beanName);方法。
没有做任何处理,应该是为了让继承的类重写方法,然后可以对获取到的object来进行处理。
这是doGetBean的方法,也是加载bean的方法。
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; // Eagerly check singleton cache for manually registered singletons. Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) { if (logger.isDebugEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // Check if bean definition exists in this factory. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. 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 { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } } //如果不仅做类型检查,这里要进行记录 if (!typeCheckOnly) { markBeanAsCreated(beanName); } try { final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } registerDependentBean(dep, beanName); getBean(dep); } } // Create bean instance. if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean. destroySingleton(beanName); throw ex; } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName); prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } catch (BeansException ex) { cleanupAfterBeanCreationFailure(beanName); throw ex; } } // Check if required type matches the type of the actual bean instance. // Note that the following return declarations are technically violating the // non-null policy for the getBean methods: However, these will only result // in null under very specific circumstances: such as a user-declared factory // method returning null or a user-provided FactoryBean.getObject() returning // null, without any custom post-processing of such null values. We will pass // them on as null to corresponding injection points in that exceptional case // but do not expect user-level getBean callers to deal with such null values. // In the end, regular getBean callers should be able to assign the outcome // to non-null variables/arguments without being compromised by rather esoteric // corner cases, in particular in functional configuration and Kotlin scenarios. // A future Spring generation might eventually forbid null values completely // and throw IllegalStateExceptions instead of leniently passing them through. if (requiredType != null && !requiredType.isInstance(bean)) { try { T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType); if (convertedBean == null) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } return convertedBean; } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } // For the nullability warning, see the elaboration in the comment above; // in short: This is never going to be null unless user-declared code enforces null. return (T) bean; }
这段代码非常长,bean对象加载的过程就是上面这个代码段。先把转换beanName,然后看看有没有缓存,若有缓存则实例化bean,若没有则看看是非是原型模式依赖的情况,检查parentBeanFactory,把gernericBeanDefinition转换成RootBeanFactory,寻找依赖,针对不同的scope创建bean,转换类型。
getSingleton函数体
protected Object getSingleton(String beanName, boolean allowEarlyReference) { Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { synchronized (this.singletonObjects) { singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) { ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } } } } return singletonObject; }
检查缓存中是否存在实例,如果为空,则从earlySingletonObjects里面获取,如果还获取不到,再尝试从SingletonFactories里面获取beanName对应的ObjectFactory,调用这个ObjectFactory来创建bean,然后放到earlySingletonObjects里面去,然后从SingletonFactories把这个beanName去掉。
getObjectForBeanInstance函数
protected Object getObjectForBeanInstance( Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) { // Don't let calling code try to dereference the factory if the bean isn't a factory. if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass()); } // Now we have the bean instance, which may be a normal bean or a FactoryBean. // If it's a FactoryBean, we use it to create a bean instance, unless the // caller actually wants a reference to the factory. if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) { return beanInstance; } Object object = null; if (mbd == null) { object = getCachedObjectForFactoryBean(beanName); } if (object == null) { // Return bean instance from factory. FactoryBean<?> factory = (FactoryBean<?>) beanInstance; // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) { mbd = getMergedLocalBeanDefinition(beanName); } boolean synthetic = (mbd != null && mbd.isSynthetic()); object = getObjectFromFactoryBean(factory, beanName, !synthetic); } return object; }
对factoryBean进行验证,对bean进行转换,将factory解析bean的工作交给getObjectFromFactoryBean完成。
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) { if (factory.isSingleton() && containsSingleton(beanName)) { synchronized (getSingletonMutex()) { Object object = this.factoryBeanObjectCache.get(beanName); if (object == null) { object = doGetObjectFromFactoryBean(factory, beanName); // Only post-process and store if not put there already during getObject() call above // (e.g. because of circular reference processing triggered by custom getBean calls) Object alreadyThere = this.factoryBeanObjectCache.get(beanName); if (alreadyThere != null) { object = alreadyThere; } else { if (shouldPostProcess) { try { object = postProcessObjectFromFactoryBean(object, beanName); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of FactoryBean's singleton object failed", ex); } } this.factoryBeanObjectCache.put(beanName, object); } } return object; } } else { Object object = doGetObjectFromFactoryBean(factory, beanName); if (shouldPostProcess) { try { object = postProcessObjectFromFactoryBean(object, beanName); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex); } } return object; } }
在这个方法体里主要保证返回的bean如果是单例就保证全局唯一性,不用重复创建单例,可以使用缓存来提高性能,以便下获取。
doGetObjectFromFactoryBean方法
private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName) throws BeanCreationException { Object object; try { if (System.getSecurityManager() != null) { AccessControlContext acc = getAccessControlContext(); try { object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> factory.getObject(), acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { object = factory.getObject(); } } catch (FactoryBeanNotInitializedException ex) { throw new BeanCurrentlyInCreationException(beanName, ex.toString()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); } // Do not accept a null value for a FactoryBean that's not fully // initialized yet: Many FactoryBeans just return null then. if (object == null) { if (isSingletonCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } object = new NullBean(); } return object; }
当bean是FactoryBean类型时,提取Bean是得到FactoryBean中的getObject方法中放回的bean。
我们拿到factory.getObject(),然后程序回到getObjectFromFactoryBean方法中,没有直接返回,而是执行了postProcessObjectFromFactoryBean(object, beanName);方法。
protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException { return object; }
没有做任何处理,应该是为了让继承的类重写方法,然后可以对获取到的object来进行处理。
相关文章推荐
- spring容器初始化,bean加载生成过程,源码解析学习
- spring源码初步学习-bean的加载
- spring源码学习(七)Bean的加载(下)
- spring源码学习(六)Bean的加载(中)
- 通过DefaultListableBeanFactory加载.xml配置文件学习Spring-IoC容器注册/加载bean的机制(源码走读)
- SSH 之 Spring的源码(一)——Bean加载过程
- spring学习总结(六):IOC & DI 配置Bean之作用域、加载外部属性文件、SPEL
- spring 源码学习笔记(一)—— spring ioc 之加载XML转换为BeanDefinition
- 分析spring源码第五(二)篇:Spring中Bean的加载
- Spring源码之bean的加载(二)获取单例bean
- spring源码学习笔记-初始化(三) registerBeanPostProcessors
- spring源码初步学习-容器(BeanFactory)基本实现
- Spring源码学习之:FactoryBean的使用
- Spring源码之bean的加载(三)从bean中获取对象
- spring源码学习之路---IOC容器初始化要义之bean定义载入(五)
- spring源码阅读之Bean的加载(一)
- Spring Bean加载源码解析
- (精)Spring IOC核心源码学习III:bean标签和自定义标签实现原理
- [spring源码学习]六、IOC源码-BeanFactory和factory-bean
- spring bean加载源码