Analysis of obtaining bean source code generated by FactoryBean by spring

Spring obtains the bean in the container through getBean, and the parameter is the corresponding beanName. Spring will first get the bean from the cache, if not, it will execute the doCreateBean method of AbstractAutowireCapableBeanFactory to create the bean (some special beans will be initialized before the call to doCreateBean, which will not be discussed here). When debugging doCreateBean, you will find that Similar to the repositories and mappers created by spring data jpa or mybatis, they will not call createBeanInstance to instantiate beans, but will be initialized beforehand.

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
      throws BeanCreationException {

   // Instantiate the bean.
   BeanWrapper instanceWrapper = null;
   if (mbd.isSingleton()) {
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
   }
   if (instanceWrapper == null) {
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }

Spring will first check whether there is a cache value corresponding to the corresponding beanName from the factoryBean Cache map of factoryBeanInstanceCache. It can be seen from the name of the attribute that the map is used to cache all factoryBean-related objects.

对于repository来说BeanWrapperImpl包装的factoryBean是JpaRepositoryFactoryBean,
对于mapper来说BeanWrapperImpl包装的factoryBean是MapperFactoryBean.
所以对于通过factoryBean构建的bean来说doCreateBean返回的就是factoryBean.

  Spring will call the AbstractBeanFactory.getObjectForBeanInstance method after creating the bean object. The function of this method is to get the object of a given bean instance. The instance can be the bean instance itself or the object created in FactoryBean. So for the returned FactoryBean object, the getObject method of FactoryBean will eventually be called to return the final bean object.

 

Guess you like

Origin blog.csdn.net/sinat_33472737/article/details/105838278