【Sping核心】BeanFactory和FactoryBean

一、什么是BeanFactory?

        BeanFactory提供了最基本的IOC容器的功能。它是一个接口类,DefaultListableBeanFactory、XmlBeanFactory、ApplicationContext等可以看成是容器附加了某些功能的具体实现。在Spring中,所以的Bean都是由BeanFactory(也就是IOC容器)来进行管理的。

public interface BeanFactory {

    String FACTORY_BEAN_PREFIX = "&";
    Object getBean(String name) throws BeansException;
     T getBean(String name, Class requiredType) throws BeansException;
    Object getBean(String name, Object... args) throws BeansException;
     T getBean(Class requiredType) throws BeansException;
     T getBean(Class requiredType, Object... args) throws BeansException;
     ObjectProvider getBeanProvider(Class requiredType);
     ObjectProvider getBeanProvider(ResolvableType requiredType);
    /**
     *  判断容器是否含有指定名字的Bean 
     */
    boolean containsBean(String name);
    /**
     *  查询指定名字的Bean是否是Singleton类型的Bean 
     */
    boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
    /**
     *  查询指定名字的Bean是否是Prototype类型的Bean 
     */
    boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
    boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
    /**
     *  查询指定名字的Bean的Class类型是否是特定的Class类
     */
    boolean isTypeMatch(String name, Class typeToMatch) throws NoSuchBeanDefinitionException;
    /**
     *  查询指定名字的Bean的Class类型
     */
    @Nullable
    Class getType(String name) throws NoSuchBeanDefinitionException;
    /**
     *  查询指定名字的Bean的所有别名 
     */
    String[] getAliases(String name);
}

二、什么是FactoryBean

       Spring 中有两种类型的Bean,一种是普通Bean,另一种是工厂Bean 即 FactoryBean。FactoryBean跟普通Bean不同,其返回的对象不是指定类的一个实例,而是该FactoryBean的getObject方法所返回的对象。创建出来的对象是否属于单例由isSingleton中的返回决定。

public interface FactoryBean {
    /**
     * 返回该FactoryBean“生产”的对象
     */
    @Nullable
    T getObject() throws Exception;
    /**
     * 该方法仅返回getObject()方法所返回的对象的类型
     */
    @Nullable
    Class getObjectType();
    /**
     * 表示“生产”的对象是否要以singleton(单例)形式存于容器中。如果以singleton形式存在,则返回true,否则返回false
     */
   //5.0之后
    default boolean isSingleton() {
        return true;
    }
   //5.0之前
    boolean isSingleton();
}

三、代码实例

public interface FactoryBeanService {
    /**
     * 测试FactoryBean
     */
    public void testFactoryBean();
}
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

@Component
public class FactoryBeanStudy implements FactoryBean {
    @Override
    public FactoryBeanService getObject() throws Exception {
        return new FactoryBeanServiceImpl();
    }

    @Override
    public Class getObjectType() {
        return FactoryBeanService.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}
import org.junit.Test;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class FactoryBeanServiceImpl implements FactoryBeanService {

    @Override
    public void testFactoryBean() {
        System.out.println("test FactoryBean");
    }

    @Test
    public void test() {
        try {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("test.xml");
        FactoryBeanService beanService = ctx.getBean(FactoryBeanService.class);
        beanService.testFactoryBean();
        System.out.println(beanService);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
输出:
test FactoryBean
com.nuc.zp.sourcecode.ioc2.FactoryBeanServiceImpl@74bf1791

四、源码分析

AbstractApplicationContext.class

@Override
	public  Map getBeansOfType(@Nullable Class type) throws BeansException {
		//检测BeanFactory的激活状态
		assertBeanFactoryActive();
		//getBeanFactory()获取到的是一个DefaultListableBeanFactory的实例
		//所以我们去DefaultListableBeanFactory中看一下getBean这个方法
		return getBeanFactory().getBeansOfType(type);
	}

DefaultListableBeanFactory.class

/**
 *  requiredType:  com.nuc.zp.sourcecode.ioc2.FactoryBeanService
 */
@Override
public  T getBean(Class requiredType) throws BeansException {
   return getBean(requiredType, (Object[]) null);
}
@SuppressWarnings("unchecked")
@Override
public  T getBean(Class requiredType, @Nullable Object... args) throws BeansException {
   Assert.notNull(requiredType, "Required type must not be null");
   //解析bean
   Object resolved = resolveBean(ResolvableType.forRawClass(requiredType), args, false);
   if (resolved == null) {
      throw new NoSuchBeanDefinitionException(requiredType);
   }
   return (T) resolved;
}
@Nullable
private  T resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) {
  //这里返回一个NamedBeanHolder,保存了对应requiredType的实例。
   NamedBeanHolder namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull);
   if (namedBean != null) {
      return namedBean.getBeanInstance();
   }
   //如果当前Spring容器中没有获取到相应的Bean信息,则从父容器中获取
   //SpringMVC是一个很典型的父子容器
   BeanFactory parent = getParentBeanFactory();
   if (parent instanceof DefaultListableBeanFactory) {
      return ((DefaultListableBeanFactory) parent).resolveBean(requiredType, args, nonUniqueAsNull);
   }
   else if (parent != null) {
      //一个重复的调用过程,只不过BeanFactory的实例变了
      ObjectProvider parentProvider = parent.getBeanProvider(requiredType);
      if (args != null) {
         return parentProvider.getObject(args);
      }
      else {
         return (nonUniqueAsNull ? parentProvider.getIfUnique() : parentProvider.getIfAvailable());
      }
   }
   return null;
}
/**
*  NamedBeanHolder 相当于一个MapM
*  beanName     为  key    即 factoryBeanStudy
*  beanInstance 为  value  即 factoryBeanService
*/
public class NamedBeanHolder implements NamedBean {

   private final String beanName;

   private final T beanInstance;


   /**
    * Create a new holder for the given bean name plus instance.
    * @param beanName the name of the bean
    * @param beanInstance the corresponding bean instance
    */
   public NamedBeanHolder(String beanName, T beanInstance) {
      Assert.notNull(beanName, "Bean name must not be null");
      this.beanName = beanName;
      this.beanInstance = beanInstance;
   }


   /**
    * Return the name of the bean.
    */
   @Override
   public String getBeanName() {
      return this.beanName;
   }

   /**
    * Return the corresponding bean instance.
    */
   public T getBeanInstance() {
      return this.beanInstance;
   }

}
/**
 *     解析Bean
 */
@SuppressWarnings("unchecked")
@Nullable
private  NamedBeanHolder resolveNamedBean(
      ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) throws BeansException {
   Assert.notNull(requiredType, "Required type must not be null");
   //这个方法是根据传入的Class类型来获取BeanName,因为我们有一个接口有多个实现类的情况(多态),
   //所以这里返回的是一个String数组。这个过程也比较复杂。
   //这里需要注意的是,我们调用getBean方法传入的type为com.nuc.zp.sourcecode.ioc2.FactoryBeanService类型,但是我们没有在Spring容器中注入FactoryBeanService类型的Bean
   //正常来说我们在这里是获取不到beanName呢。但是事实是不是这样呢?看下面我们对getBeanNamesForType的分析

   String[] candidateNames = getBeanNamesForType(requiredType);
   //如果有多个BeanName,则挑选合适的BeanName
   if (candidateNames.length > 1) {
      List autowireCandidates = new ArrayList<>(candidateNames.length);
      for (String beanName : candidateNames) {
         if (!containsBeanDefinition(beanName) || getBeanDefinition(beanName).isAutowireCandidate()) {
            autowireCandidates.add(beanName);
         }
      }
      if (!autowireCandidates.isEmpty()) {
         candidateNames = StringUtils.toStringArray(autowireCandidates);
      }
   }
   //如果只有一个BeanName 我们调用getBean方法来获取Bean实例来放入到NamedBeanHolder中
   //这里获取bean是根据beanName,beanType和args来获取bean
   if (candidateNames.length == 1) {
      String beanName = candidateNames[0];//factoryBeanStudy
     //这里的getBean方法,最终会调用到FactoryBean的getObjectType方法,所以会得到factoryBeanService的实例
      return new NamedBeanHolder<>(beanName, (T) getBean(beanName, requiredType.toClass(), args));
   }
   //如果合适的BeanName还是有多个的话
   else if (candidateNames.length > 1) {
      Map candidates = new LinkedHashMap<>(candidateNames.length);
      for (String beanName : candidateNames) {
         //看看是不是已经创建多的单例Bean
         if (containsSingleton(beanName) && args == null) {
            Object beanInstance = getBean(beanName);
            candidates.put(beanName, (beanInstance instanceof NullBean ? null : beanInstance));
         }
         else {
            //调用getType方法继续获取Bean实例
            candidates.put(beanName, getType(beanName));
         }
      }
      //有多个Bean实例的话 则取带有Primary注解或者带有Primary信息的Bean
      String candidateName = determinePrimaryCandidate(candidates, requiredType.toClass());
      if (candidateName == null) {
         candidateName = determineHighestPriorityCandidate(candidates, requiredType.toClass());
      }
      if (candidateName != null) {
         Object beanInstance = candidates.get(candidateName);
         //Class类型的话 继续调用getBean方法获取Bean实例
         if (beanInstance == null || beanInstance instanceof Class) {
            beanInstance = getBean(candidateName, requiredType.toClass(), args);
         }
         return new NamedBeanHolder<>(candidateName, (T) beanInstance);
      }
      if (!nonUniqueAsNull) {
         //都没有获取到 抛出异常
         throw new NoUniqueBeanDefinitionException(requiredType, candidates.keySet());
      }
   }
@Override
public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
   Class resolved = type.resolve();
   if (resolved != null && !type.hasGenerics()) {
      return getBeanNamesForType(resolved, includeNonSingletons, includeNonSingletons);
   }
   else {
      return doGetBeanNamesForType(type, includeNonSingletons, includeNonSingletons);
   }
}
@Override
public String[] getBeanNamesForType(@Nullable Class type, boolean includeNonSingletons, boolean allowEagerInit) {
   if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
      return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
   }
   //先从缓存中获取
   Map, String[]> cache =
         (includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType);
   String[] resolvedBeanNames = cache.get(type);
   if (resolvedBeanNames != null) {
      return resolvedBeanNames;
   }
   //调用doGetBeanNamesForType方法获取beanName
   resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true);
   //所传入的类能不能被当前类加载加载
   if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) {
      //放入到缓存中,解析一次以后从缓存中获取
      cache.put(type, resolvedBeanNames);
   }
   return resolvedBeanNames;
}

 

private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
   List result = new ArrayList<>();
   //循环所有的beanName 这个是在Spring容器启动解析Bean的时候放入到这个List中的
   // Check all bean definitions.
   for (String beanName : this.beanDefinitionNames) {
      // Only consider bean as eligible if the bean name
      // is not defined as alias for some other bean.
      if (!isAlias(beanName)) {
         try {
            //根据beanName获取RootBeanDefinition
            RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            // Only check bean definition if it is complete.
            //RootBeanDefinition中的Bean不是抽象类、非延迟初始化
            if (!mbd.isAbstract() && (allowEagerInit ||
                  (mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
                        !requiresEagerInitForType(mbd.getFactoryBeanName()))) {
               //是不是FactoryBean的子类
               boolean isFactoryBean = isFactoryBean(beanName, mbd);
               BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
               //这里我们其他的几个变量的意思都差不多  我们需要重点关注的是isTypeMatch这个方法
               //如果isTypeMatch这个方法返回true的话,我们会把这个beanName即factoryBeanStudy 放入到result中返回
               boolean matchFound = false;
               boolean allowFactoryBeanInit = allowEagerInit || containsSingleton(beanName);
               boolean isNonLazyDecorated = dbd != null && !mbd.isLazyInit();
               if (!isFactoryBean) {
                  //如果不匹配,还是FactoryBean的子类 这里会把beanName变为 &beanName
                  if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
                     //判断类型匹配不匹配
                     matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
                  }
               }
               else  {
                  if (includeNonSingletons || isNonLazyDecorated ||
                        (allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) {
                     matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
                  }
                  if (!matchFound) {
                     // In case of FactoryBean, try to match FactoryBean instance itself next.
                     beanName = FACTORY_BEAN_PREFIX + beanName;
                     matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
                  }
               }
               if (matchFound) {
                  result.add(beanName);
               }
            }
         }
         catch (CannotLoadBeanClassException | BeanDefinitionStoreException ex) {
            if (allowEagerInit) {
               throw ex;
            }
            // Probably a placeholder: let's ignore it for type matching purposes.
            LogMessage message = (ex instanceof CannotLoadBeanClassException) ?
                  LogMessage.format("Ignoring bean class loading failure for bean '%s'", beanName) :
                  LogMessage.format("Ignoring unresolvable metadata in bean definition '%s'", beanName);
            logger.trace(message, ex);
            onSuppressedException(ex);
         }
      }
   }


   //这里的Bean是Spring容器创建的特殊的几种类型的Bean 像Environment
   // Check manually registered singletons too.
   for (String beanName : this.manualSingletonNames) {
      try {
         // In case of FactoryBean, match object created by FactoryBean.
         if (isFactoryBean(beanName)) {
            if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
               result.add(beanName);
               // Match found for this bean: do not match FactoryBean itself anymore.
               continue;
            }
            // In case of FactoryBean, try to match FactoryBean itself next.
            beanName = FACTORY_BEAN_PREFIX + beanName;
         }
         // Match raw bean instance (might be raw FactoryBean).
         if (isTypeMatch(beanName, type)) {
            result.add(beanName);
         }
      }
      catch (NoSuchBeanDefinitionException ex) {
         // Shouldn't happen - probably a result of circular reference resolution...
         logger.trace(LogMessage.format("Failed to check manually registered singleton with name '%s'", beanName), ex);
      }
   }

   return StringUtils.toStringArray(result);
}
boolean isTypeMatch(String name, ResolvableType typeToMatch,
      boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException {
   //转换beanName   这里我们可以知道我们的beanName为factoryBeanStudy 因为上面是循环了Spring容器中的所有的Bean
   String beanName = transformedBeanName(name);
   boolean isFactoryDereference = BeanFactoryUtils.isFactoryDereference(name);
   //因为我们这里是用的AbstractApplicationContext的子类来从Spring容器中获取Bean
   //获取beanName为factoryBeanStudy的Bean实例 这里是可以获取到Bean实例的
   //这里有一个问题:使用AbstractApplicationContext的子类从Spring容器中获取Bean和
   //使用BeanFactory的子类从容器中获取Bean有什么区别?这个可以思考一下

   // Check manually registered singletons.
   Object beanInstance = getSingleton(beanName, false);
   if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
      //factoryBeanStudy是FactoryBean的一个实现类
      if (beanInstance instanceof FactoryBean) {
         //这里判断beanName是不是以&开头  这里明显不是 这里可以想一下什么情况下会有&开头的Bean
         if (!isFactoryDereference) {
            //这里就是从factoryBeanStudy中获type类型 我们在下面会分析一下这个类
            Class type = getTypeForFactoryBean((FactoryBean) beanInstance);
            //从factoryBeanLearn中获取到的type类型和我们传入的类型是不是同一种类型 是的话直接返回
            return (type != null && typeToMatch.isAssignableFrom(type));
         }
         else {
            return typeToMatch.isInstance(beanInstance);
         }
      }
      else if (!isFactoryDereference) {
         if (typeToMatch.isInstance(beanInstance)) {
            // Direct match for exposed instance?
            return true;
         }
         else if (typeToMatch.hasGenerics() && containsBeanDefinition(beanName)) {
            // Generics potentially only match on the target class, not on the proxy...
            RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            Class targetType = mbd.getTargetType();
            if (targetType != null && targetType != ClassUtils.getUserClass(beanInstance)) {
               // Check raw class match as well, making sure it's exposed on the proxy.
               Class classToMatch = typeToMatch.resolve();
               if (classToMatch != null && !classToMatch.isInstance(beanInstance)) {
                  return false;
               }
               if (typeToMatch.isAssignableFrom(targetType)) {
                  return true;
               }
            }
            ResolvableType resolvableType = mbd.targetType;
            if (resolvableType == null) {
               resolvableType = mbd.factoryMethodReturnType;
            }
            return (resolvableType != null && typeToMatch.isAssignableFrom(resolvableType));
         }
      }
      return false;
   }
   else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
      // null instance registered
      return false;
   }

   // No singleton instance found -> check bean definition.
   BeanFactory parentBeanFactory = getParentBeanFactory();
   if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
      // No bean definition found in this factory -> delegate to parent.
      return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);
   }

   // Retrieve corresponding bean definition.
   RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
   BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();

   // Setup the types that we want to match against
   Class classToMatch = typeToMatch.resolve();
   if (classToMatch == null) {
      classToMatch = FactoryBean.class;
   }
   Class[] typesToMatch = (FactoryBean.class == classToMatch ?
         new Class[] {classToMatch} : new Class[] {FactoryBean.class, classToMatch});


   // Attempt to predict the bean type
   Class predictedType = null;

   // We're looking for a regular reference but we're a factory bean that has
   // a decorated bean definition. The target bean should be the same type
   // as FactoryBean would ultimately return.
   if (!isFactoryDereference && dbd != null && isFactoryBean(beanName, mbd)) {
      // We should only attempt if the user explicitly set lazy-init to true
      // and we know the merged bean definition is for a factory bean.
      if (!mbd.isLazyInit() || allowFactoryBeanInit) {
         RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
         Class targetType = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
         if (targetType != null && !FactoryBean.class.isAssignableFrom(targetType)) {
            predictedType = targetType;
         }
      }
   }

   // If we couldn't use the target type, try regular prediction.
   if (predictedType == null) {
      predictedType = predictBeanType(beanName, mbd, typesToMatch);
      if (predictedType == null) {
         return false;
      }
   }

   // Attempt to get the actual ResolvableType for the bean.
   ResolvableType beanType = null;

   // If it's a FactoryBean, we want to look at what it creates, not the factory class.
   if (FactoryBean.class.isAssignableFrom(predictedType)) {
      if (beanInstance == null && !isFactoryDereference) {
         beanType = getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit);
         predictedType = beanType.resolve();
         if (predictedType == null) {
            return false;
         }
      }
   }
   else if (isFactoryDereference) {
      // Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean
      // type but we nevertheless are being asked to dereference a FactoryBean...
      // Let's check the original bean class and proceed with it if it is a FactoryBean.
      predictedType = predictBeanType(beanName, mbd, FactoryBean.class);
      if (predictedType == null || !FactoryBean.class.isAssignableFrom(predictedType)) {
         return false;
      }
   }

   // We don't have an exact type but if bean definition target type or the factory
   // method return type matches the predicted type then we can use that.
   if (beanType == null) {
      ResolvableType definedType = mbd.targetType;
      if (definedType == null) {
         definedType = mbd.factoryMethodReturnType;
      }
      if (definedType != null && definedType.resolve() == predictedType) {
         beanType = definedType;
      }
   }

   // If we have a bean type use it so that generics are considered
   if (beanType != null) {
      return typeToMatch.isAssignableFrom(beanType);
   }

   // If we don't have a bean type, fallback to the predicted type
   return typeToMatch.isAssignableFrom(predictedType);
}

        上面的分析总结起来是:我们调用getBean(Class requiredType)方法根据类型来获取容器中的bean的时候,对应我们的例子就是:根据类型FactoryBeanService来从Spring容器中获取Bean(首先明确的一点是在Spring容器中没有FactoryBeanService类型的BeanDefinition。但是却有一个Bean和FactoryBeanService这个类型有一些关系)。Spring在根据type去获取Bean的时候,会先获取到beanName。获取beanName的过程是:先循环Spring容器中的所有的beanName,然后根据beanName获取对应的BeanDefinition,如果当前bean是FactoryBean的类型,则会从Spring容器中根据beanName获取对应的Bean实例,接着调用获取到的Bean实例的getObjectType方法获取到Class类型,判断此Class类型和我们传入的Class是否是同一类型。如果是则返回测beanName,对应到我们这里就是:根据factoryBeanStudy获取到FactoryBeanStudy实例,调用FactoryBeanStudy的getObjectType方法获取到返回值FactoryBeanService.class。和我们传入的类型一致,所以这里获取的beanName为factoryBeanStudy。换句话说这里我们把factoryBeanStudy这个beanName映射为了:FactoryBeanService类型。即FactoryBeanService类型对应的beanName为factoryBeanStudy这是很重要的一点。

五、总结

         BeanFactory中可以创建和管理Spring容器中的Bean,它对于Bean的创建有一个统一的流程。FactoryBean是一个工厂Bean,可以生成某一个类型Bean实例,它最大的一个作用是:可以让我们自定义Bean的创建过程。

你可能感兴趣的:(Spring)