@Test publicvoidtest(){ DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); reader.loadBeanDefinitions("META-INF/spring-bean.xml"); User user = beanFactory.getBean("user", User.class); System.out.println(user); }
/** * @param name bean的名称 * @param requiredType bean的类型 */ public <T> T getBean(String name, Class<T> requiredType)throws BeansException { // 调用 doGetBean 方法(方法以do开头实际做操作的方法) return doGetBean(name, requiredType, null, false); }
/** * @param name bean的名称 * @param requiredType bean的类型 * @param args 显示传入的构造参数 * @param typeCheckOnly 是否仅仅做类型检查 */ protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly)throws BeansException { // 获取bean的实际名称,见下文详解 final String beanName = transformedBeanName(name); Object bean;
// Eagerly check singleton cache for manually registered singletons. // 直接尝试从缓存获取或 singletonFactories 中的 ObjectFactory 中获取,见下文详解 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是否是FactoryBean的实现。不是直接返回bean,是的话首先检查beanName是否以 & 开头 // 如果是返回FactoryBean本身,不是调用FactoryBean#getObject()返回对象 // 见下文详解 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); }
else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. // 只有在单例情况下才会去尝试解决循环依赖,原型模式下,如果存在A中有 // B属性,B中有A属性,那么当依赖注入时,就会产生当A还未创建完的时候 // 对于B的创建而在此返回创建A,造成循环依赖 if (isPrototypeCurrentlyInCreation(beanName)) { thrownew BeanCurrentlyInCreationException(beanName); }
// Check if bean definition exists in this factory. // 检查当前bean的BeanDefinition是否在当前的beanFactory,不在递归调用父工厂的getBean()去获取bean 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); } elseif (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } elseif (requiredType != null) { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } else { return (T) parentBeanFactory.getBean(nameToLookup); } } // 如果不是仅仅做类型检查,则是创建bean,这里要进行记录 if (!typeCheckOnly) { // 记录bean已经创建过,见下文详解 markBeanAsCreated(beanName); }
// Don't let calling code try to dereference the factory if the bean isn't a factory. // name 是否以 & 开头 if (BeanFactoryUtils.isFactoryDereference(name)) { // 如果是 null 直接返回 if (beanInstance instanceof NullBean) { return beanInstance; } // beanName 以 & 开头,但又不是 FactoryBean 类型,抛出异常 if (!(beanInstance instanceof FactoryBean)) { thrownew BeanIsNotAFactoryException(beanName, beanInstance.getClass()); } // 设置 isFactoryBean 为 true if (mbd != null) { mbd.isFactoryBean = true; } // 返回 bean 实例 return beanInstance; }
// 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. // name 不是 & 开头,并且不是 FactoryBean 类型,直接返回 if (!(beanInstance instanceof FactoryBean)) { return beanInstance; }
Object object = null; if (mbd != null) { mbd.isFactoryBean = true; } else { // 从缓存中获取实例 object = getCachedObjectForFactoryBean(beanName); } if (object == null) { // Return bean instance from factory. // 将 beanInstance 强转成 FactoryBean FactoryBean<?> factory = (FactoryBean<?>) beanInstance; // Caches object obtained from FactoryBean if it is a singleton. // 合并 BeanDefinition if (mbd == null && containsBeanDefinition(beanName)) { mbd = getMergedLocalBeanDefinition(beanName); } boolean synthetic = (mbd != null && mbd.isSynthetic()); // 获取实例 object = getObjectFromFactoryBean(factory, beanName, !synthetic); } return object; }
// Do not accept a null value for a FactoryBean that's not fully // initialized yet: Many FactoryBeans just return null then. // 如果 object 为 null,并且当前 singleton bean 正在创建中,抛出异常 if (object == null) { if (isSingletonCurrentlyInCreation(beanName)) { thrownew BeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } object = new NullBean(); } // 返回 object 实例 return object; }
// Check with full lock now in order to enforce the same merged instance. // 如果bean是顶级bean,直接获取合并后的BeanDefinition if (containingBd == null) { mbd = this.mergedBeanDefinitions.get(beanName); } // 没有合并后的BeanDefinition || BeanDefinition过期了 if (mbd == null || mbd.stale) { previous = mbd; // 如果bean没有parent if (bd.getParentName() == null) { // Use copy of given root bean definition. // 如果bd本身就是RootBeanDefinition直接复制一份,否则创建一个 if (bd instanceof RootBeanDefinition) { mbd = ((RootBeanDefinition) bd).cloneBeanDefinition(); } else { mbd = new RootBeanDefinition(bd); } } else { // Child bean definition: needs to be merged with parent. // bean有parent BeanDefinition pbd; try { // 获取parent bean的实际名称 String parentBeanName = transformedBeanName(bd.getParentName()); if (!beanName.equals(parentBeanName)) { // 当前beanName不等于它的parent beanName // 获取parent合并后的BeanDefinition pbd = getMergedBeanDefinition(parentBeanName); } else { // 如果父定义的beanName与bd的beanName相同,则拿到父BeanFactory // 只有在存在父BeanFactory的情况下,才允许父定义beanName与自己相同 BeanFactory parent = getParentBeanFactory(); if (parent instanceof ConfigurableBeanFactory) { // 如果父BeanFactory是ConfigurableBeanFactory // 则通过父BeanFactory获取parent合并后的BeanDefinition pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName); } else { // 如果父BeanFactory不是ConfigurableBeanFactory,抛出异常 thrownew NoSuchBeanDefinitionException(parentBeanName, "Parent name '" + parentBeanName + "' is equal to bean name '" + beanName + "': cannot be resolved without an AbstractBeanFactory parent"); } } } catch (NoSuchBeanDefinitionException ex) { thrownew BeanDefinitionStoreException(bd.getResourceDescription(), beanName, "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex); } // Deep copy with overridden values. // 使用父定义pbd构建一个新的RootBeanDefinition对象(深拷贝) mbd = new RootBeanDefinition(pbd); // 覆盖与parent相同的属性, mbd.overrideFrom(bd); } // Set default singleton scope, if not configured before. // 如果bean没有设置scope属性,默认是singleton if (!StringUtils.hasLength(mbd.getScope())) { mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON); }
// A bean contained in a non-singleton bean cannot be a singleton itself. // Let's correct this on the fly here, since this might be the result of // parent-child merging for the outer bean, in which case the original inner bean // definition will not have inherited the merged outer bean's singleton status. // 当前bean是嵌套bean && 顶级bean的作用域不是单例 && 当前bean的作用域是单例 // 这里总结起来就是,如果顶层bean不是单例的,那么嵌套bean也不能是单例的 if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) { // 设置当前bean的作用域和顶级bean一样 mbd.setScope(containingBd.getScope()); }
// Cache the merged bean definition for the time being // (it might still get re-merged later on in order to pick up metadata changes) // 当前bean是顶级bean && 缓存bean的元数据(该值默认为true) if (containingBd == null && isCacheBeanMetadata()) { // 将当前bean合并后的RootBeanDefinition缓存起来 this.mergedBeanDefinitions.put(beanName, mbd); } } // 以前的RootBeanDefinition不为空,拷贝相关的BeanDefinition缓存 if (previous != null) { copyRelevantMergedBeanDefinitionCaches(previous, mbd); } return mbd; } }