1、根据beanName可以从Spring的三级缓存中获取到bean对象

  1. protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
  2. @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
  3. // 如果这个 name 是 FactoryBean 的beanName (&+beanName),就删除& , 返回beanName ,传入的name也可以是别名,也需要做转换
  4. // 注意 beanName 和 name 变量的区别,beanName是经过处理的,经过处理的beanName就直接对应singletonObjects中的key
  5. final String beanName = transformedBeanName(name);
  6. Object bean;
  7. // Eagerly check singleton cache for manually registered singletons.
  8. // 根据beanName尝试从singletonObjects获取Bean
  9. // 获取不到则再尝试从earlySingletonObjects,singletonFactories 从获取Bean
  10. // 这段代码和解决循环依赖有关
  11. Object sharedInstance = getSingleton(beanName);
  12. // 第一次进入sharedInstance肯定为null
  13. if (sharedInstance != null && args == null) {
  14. // 如果sharedInstance不为null,也就是非第一次进入
  15. // 为什么要调用 getObjectForBeanInstance 方法,判断当前Bean是不是FactoryBean,如果是,那么要不要调用getObject方法
  16. // 因为传入的name变量如果是(&+beanName),那么beanName变量就是(beanName),也就是说,程序在这里要返回FactoryBean
  17. // 如果传入的name变量(beanName),那么beanName变量也是(beanName),但是,之前获取的sharedInstance可能是FactoryBean,需要通过sharedInstance来获取对应的Bean
  18. // 如果传入的name变量(beanName),那么beanName变量也是(beanName),获取的sharedInstance就是对应的Bean的话,就直接返回Bean
  19. bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);

2、如果是首次进入sharedInstance==null

  1. // 判断是否循环依赖
  2. if (isPrototypeCurrentlyInCreation(beanName)) {
  3. throw new BeanCurrentlyInCreationException(beanName);
  4. }
  5. // Check if bean definition exists in this factory.
  6. // 获取父BeanFactory,一般情况下,父BeanFactory为null,如果存在父BeanFactory,就先去父级容器去查找
  7. BeanFactory parentBeanFactory = getParentBeanFactory();
  8. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  9. // Not found -> check parent.
  10. String nameToLookup = originalBeanName(name);
  11. if (parentBeanFactory instanceof AbstractBeanFactory) {
  12. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  13. nameToLookup, requiredType, args, typeCheckOnly);
  14. } else if (args != null) {
  15. // Delegation to parent with explicit args.
  16. return (T) parentBeanFactory.getBean(nameToLookup, args);
  17. } else if (requiredType != null) {
  18. // No args -> delegate to standard getBean method.
  19. return parentBeanFactory.getBean(nameToLookup, requiredType);
  20. } else {
  21. return (T) parentBeanFactory.getBean(nameToLookup);
  22. }
  23. }

关于判断循环依赖,可以参考