Spring Bean 的实例化过程
------------------2020.7.27
bean 创建的三步走:
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory createBean() --> doCreateBean() 1. createBeanInstance() // 通过反射创建 bean 的实例 2. populateBean() // 填充 bean 里面的属性值,包括 @AutoWired、@Resource、@Value 标记的属性 3. initializeBean() // 对 bean 进行初始化工作,包括一些初始化方法的执行,如:awareMethods、BeanPostProcessor、initMethods // 参考方法:AbstractAutowireCapableBeanFactory#initializeBean() // 其中,@ConfigurationProperties 标记的 bean 的属性注入,就选择了使用 BeanPostProcessor 来处理 // 具体的处理可查看 ConfigurationPropertiesBindingPostProcessor#postProcessBeforeInitialization()
-------------------2020.1.6
Spring Bean 的初始化是在 Spring 容器 refresh() 时进行的。
Spring 容器 refresh 时会调用 finishBeanFactoryInitialization() 来初始化所有非延迟加载的 bean。
1 org.springframework.context.support.AbstractApplicationContext.refresh() 2 --> org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization // 初始化bean(延迟加载除外) 3 --> org.springframework.beans.factory.config.ConfigurableListableBeanFactory.preInstantiateSingletons() 4 --> org.springframework.beans.factory.support.AbstractBeanFactory.getBean 5 --> org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean 6 --> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean // 创建 bean(实例化 bean)
1. org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean
0. pre: 如果 bean 已经注册过,就从缓存中获取 bean 的实例
1. 在 parentBeanFactory 中如果存在 beanName,则直接返回父容器里面的 bean
2. 初始化当前 bean 依赖的 bean
3. 创建 bean 的实例
3.1 单例类型的 bean 创建
3.2 原型类型的 bean 创建
3.3 其他 scope 类型(request、session等)的 bean 创建
4. 将新创建的 bean 的实例保存到缓存 singletonObjects 中
1 protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { 2 3 final String beanName = transformedBeanName(name); 4 Object bean; 5 6 // Eagerly check singleton cache for manually registered singletons. 7 // 从缓存中获取 bean 的实例(已经注册过的 bean 都保存在 singletonObjects 中) 8 Object sharedInstance = getSingleton(beanName); 9 if (sharedInstance != null && args == null) { 10 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); 11 } else { 12 13 // Check if bean definition exists in this factory. 14 // 1. 在 parentBeanFactory 中如果存在 beanName,则直接返回父容器里面的 bean 15 BeanFactory parentBeanFactory = getParentBeanFactory(); 16 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { 17 // Not found -> check parent. 18 String nameToLookup = originalBeanName(name); 19 if (parentBeanFactory instanceof AbstractBeanFactory) { 20 return ((AbstractBeanFactory) parentBeanFactory).doGetBean( 21 nameToLookup, requiredType, args, typeCheckOnly); 22 } else if (args != null) { 23 // Delegation to parent with explicit args. 24 return (T) parentBeanFactory.getBean(nameToLookup, args); 25 } else if (requiredType != null) { 26 // No args -> delegate to standard getBean method. 27 return parentBeanFactory.getBean(nameToLookup, requiredType); 28 } else { 29 return (T) parentBeanFactory.getBean(nameToLookup); 30 } 31 } 32 33 try { 34 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); 35 checkMergedBeanDefinition(mbd, beanName, args); 36 37 // Guarantee initialization of beans that the current bean depends on. 38 // 2. 初始化当前 bean 依赖的 bean 39 String[] dependsOn = mbd.getDependsOn(); 40 if (dependsOn != null) { 41 for (String dep : dependsOn) { 42 if (isDependent(beanName, dep)) { 43 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); 44 } 45 registerDependentBean(dep, beanName); 46 try { 47 // getBean() 会再递归调用 doGetBean(),以确保所依赖的 bean 全部初始化 48 getBean(dep); 49 } 50 catch (NoSuchBeanDefinitionException ex) { 51 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); 52 } 53 } 54 } 55 56 // Create bean instance. 57 // 3. 创建 bean 的实例 58 if (mbd.isSingleton()) { // 单例类型的 bean 59 sharedInstance = getSingleton(beanName, () -> { 60 try { 61 // 创建 bean 的实例 62 return createBean(beanName, mbd, args); 63 } catch (BeansException ex) { 64 destroySingleton(beanName); 65 throw ex; 66 } 67 }); 68 // 如果 bean 为 FactoryBean 的话,则调用 FactoryBean.getObject() 来创建 bean 实例 69 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); 70 } else if (mbd.isPrototype()) { // 原型类型的 bean 71 // It's a prototype -> create a new instance. 72 Object prototypeInstance = null; 73 try { 74 beforePrototypeCreation(beanName); 75 prototypeInstance = createBean(beanName, mbd, args); 76 } finally { 77 afterPrototypeCreation(beanName); 78 } 79 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); 80 } else { // 其他 scope 类型的 bean 81 String scopeName = mbd.getScope(); 82 final Scope scope = this.scopes.get(scopeName); 83 if (scope == null) { 84 throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); 85 } 86 try { 87 Object scopedInstance = scope.get(beanName, () -> { 88 beforePrototypeCreation(beanName); 89 try { 90 return createBean(beanName, mbd, args); 91 } finally { 92 afterPrototypeCreation(beanName); 93 } 94 }); 95 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); 96 } catch (IllegalStateException ex) { 97 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); 98 } 99 } 100 } 101 catch (BeansException ex) { 102 cleanupAfterBeanCreationFailure(beanName); 103 throw ex; 104 } 105 } 106 107 ...... 108 return (T) bean; 109 }
2. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean
1 protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) 2 throws BeanCreationException { 3 4 RootBeanDefinition mbdToUse = mbd; 5 ...... 6 7 // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. 8 // BeanPostProcessor 可以创建一个代理 bean 返回 9 // 执行 InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation -- bean 实例化前置处理 10 // 执行 InstantiationAwareBeanPostProcessor.postProcessAfterInitialization -- bean 初始化后置处理 11 Object bean = resolveBeforeInstantiation(beanName, mbdToUse); 12 if (bean != null) { 13 return bean; 14 } 15 16 // 创建 bean 17 Object beanInstance = doCreateBean(beanName, mbdToUse, args); 18 return beanInstance; 19 }
代理 bean 是通过 AbstractAutoProxyCreator 来创建的:
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(Class<?> beanClass, String beanName)
1 public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) { 2 Object cacheKey = getCacheKey(beanClass, beanName); 3 4 if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) { 5 if (this.advisedBeans.containsKey(cacheKey)) { 6 return null; 7 } 8 if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { 9 this.advisedBeans.put(cacheKey, Boolean.FALSE); 10 return null; 11 } 12 } 13 14 // Create proxy here if we have a custom TargetSource. 15 // Suppresses unnecessary default instantiation of the target bean: 16 // The TargetSource will handle target instances in a custom fashion. 17 TargetSource targetSource = getCustomTargetSource(beanClass, beanName); 18 if (targetSource != null) { 19 if (StringUtils.hasLength(beanName)) { 20 this.targetSourcedBeans.add(beanName); 21 } 22 Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource); 23 Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource); 24 this.proxyTypes.put(cacheKey, proxy.getClass()); 25 return proxy; 26 } 27 28 return null; 29 }
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(@Nullable Object bean, String beanName)
1 /** 2 * Create a proxy with the configured interceptors if the bean is 3 * identified as one to proxy by the subclass. 4 * @see #getAdvicesAndAdvisorsForBean 5 */ 6 @Override 7 public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) { 8 if (bean != null) { 9 Object cacheKey = getCacheKey(bean.getClass(), beanName); 10 if (this.earlyProxyReferences.remove(cacheKey) != bean) { 11 return wrapIfNecessary(bean, beanName, cacheKey); 12 } 13 } 14 return bean; 15 } 16 17 protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { 18 if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) { 19 return bean; 20 } 21 if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { 22 return bean; 23 } 24 if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { 25 this.advisedBeans.put(cacheKey, Boolean.FALSE); 26 return bean; 27 } 28 29 // Create proxy if we have advice. 30 Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); 31 if (specificInterceptors != DO_NOT_PROXY) { 32 this.advisedBeans.put(cacheKey, Boolean.TRUE); 33 Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); 34 this.proxyTypes.put(cacheKey, proxy.getClass()); 35 return proxy; 36 } 37 38 this.advisedBeans.put(cacheKey, Boolean.FALSE); 39 return bean; 40 }
3. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
1 protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException { 2 3 // Instantiate the bean. 4 BeanWrapper instanceWrapper = null; 5 6 if (instanceWrapper == null) { 7 // 创建 bean 的实例:通过默认构造函数反射生成、通过配置的构造函数生成(构造方法注入)、通过 factoryMethod 生成 8 // 最终会生成一个 BeanWrapper 9 instanceWrapper = createBeanInstance(beanName, mbd, args); 10 } 11 final Object bean = instanceWrapper.getWrappedInstance(); 12 Class<?> beanType = instanceWrapper.getWrappedClass(); 13 14 // Allow post-processors to modify the merged bean definition. 15 // 允许 post-processors 修改 bean 的定义 16 synchronized (mbd.postProcessingLock) { 17 if (!mbd.postProcessed) { 18 // 执行 MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition 19 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 20 mbd.postProcessed = true; 21 } 22 } 23 24 // Eagerly cache singletons to be able to resolve circular references 25 // even when triggered by lifecycle interfaces like BeanFactoryAware. 26 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); 27 if (earlySingletonExposure) { 28 // 解决循环依赖相关 29 addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); 30 } 31 32 // Initialize the bean instance. 33 Object exposedObject = bean; 34 try { 35 // 填充 bean 属性,处理属性注入:@Value, @Autowired, @Resource 等 36 populateBean(beanName, mbd, instanceWrapper); 37 // 初始化 bean:执行 aware 方法 --> BeanPostProcessor --> afterPropertiesSet() --> 指定的初始化方法 38 exposedObject = initializeBean(beanName, exposedObject, mbd); 39 } catch (Throwable ex) { 40 if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { 41 throw (BeanCreationException) ex; 42 } 43 else { 44 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); 45 } 46 } 47 48 ...... 49 50 return exposedObject; 51 }