Spring的bean的生命周期
spring要了解的几个类
AbstractApplicationContext: 启动类,spring开始方法执行refresh()十几步方法
beanPostProcessor: bean的增强器,两个接口before,after,初始化之前执行beforeInitializationa,初始化之后执行fterInitialization,
InstantiationAwareBeanPostProcessor: bean的实例化增强器,实现beanPostProcessor,自己新增实例化两个接口,实例化之前执行postProcessBeforeInstantiation,实例化之后执行postProcessAfterInstantiation
AbstractBeanFactory: 实现默认 bean 创建的抽象 bean 工厂超类,createBean、initializeBean、
AnnotationAwareAspectJAutoProxyCreator: 是AOP代理增强器(@EnableAspectJAutoProxy把它注册进来的)
DefaultListableBeanFactory: 监听工厂,实现了AbstractBeanFactory,其中beanFactory、beanDefinitionMap等等
Spring的bean生命周期
1、把xml、@bean、@Component的bean放进Map<String, BeanDefinition> beanDefinitionMap中,bean的类名放进List<String> beanDefinitionNames中
2、会提前初始化和实例化自定义和spring自带的增强器beanPostProcessor 在refresh().registerBeanPostProcessors()
3、通过遍历bean进行实例化createBeanInstance(beanName, mbd, args)并且调用并调用构造方法
4、放入三级缓存中singletonFactories,提前暴露 ,目的为了不用重复创建bean,放在工厂方便bean的扩展addSingletonFactory()
5、填充属性populateBean(beanName, mbd, instanceWrapper)
6、初始化bean之前,执行增强器before 方法 BeforeInitialization
7、初始化bean,包括postProcessor增强器(@PostConstruct在这里执行),方法invokeInitMethods(beanName, wrappedBean, mbd)
8、初始化bean之后,执行增强器before方法 AfterInitialization,方法applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName) ,其中AOP就是在这里给bean替换成代理对象
9:销毁过程
1、启动执行AbstractApplicationContext的refresh()下面的十几个方法
接下来会挑几个重点的方法看
AbstractApplicationContext 重点
1 public void refresh() throws BeansException, IllegalStateException { 2 synchronized (this.startupShutdownMonitor) { 3 4 // 准备此上下文以进行刷新。 5 // 1、初始化 环境变量 initPropertySources ,getEnvironment 6 prepareRefresh(); 7 8 // Tell the subclass to refresh the internal bean factory. 9 // 2 、 beandefinition 初始化, 把class存放在 beandefinitionMap中 10 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 11 12 // 准备在此上下文中使用的 bean 工厂. 13 // 3、初始化registerSingleton 格式化工厂、比如把系统的单例bean 添加到 单例缓存池中 14 prepareBeanFactory(beanFactory); 15 16 try { 17 // 4、在标准初始化之后修改应用程序上下文的内部 bean 工厂。 所有 bean 定义都将被加载,但尚未实例化任何 bean。 18 // 这允许在某些 ApplicationContext 实现中注册特殊的 BeanPostProcessor 等 19 postProcessBeanFactory(beanFactory); 20 21 // 5、 调用在上下文中注册为 bean 的工厂处理器 22 invokeBeanFactoryPostProcessors(beanFactory); 23 24 // 6、注册拦截 bean 创建的 bean处理器,把增强器postProcessor实例化和初始化 25 registerBeanPostProcessors(beanFactory); 26 27 // Initialize message source for this context. 28 // 7、 国际化 29 initMessageSource(); 30 31 // 8、 为此上下文初始化事件多播器。 32 initApplicationEventMulticaster(); 33 34 // 8、可以覆盖的模板方法以添加特定于上下文的刷新工作。 在单例实例化之前调用特殊 bean 的初始化。这个实现是空的 35 onRefresh(); 36 37 // 9、添加实现 ApplicationListener 作为侦听器的 bean。 不影响其他监听器,可以不加bean。 38 registerListeners(); 39 40 // 10、实例化、初始化bean 41 finishBeanFactoryInitialization(beanFactory); 42 43 // Last step: publish corresponding event. 44 // 11、最后一步:发布相应的事件 45 finishRefresh(); 46 } 47 48 catch (BeansException ex) { 49 if (logger.isWarnEnabled()) { 50 logger.warn("Exception encountered during context initialization - " + 51 "cancelling refresh attempt: " + ex); 52 } 53 54 // Destroy already created singletons to avoid dangling resources. 55 destroyBeans(); 56 57 // Reset 'active' flag. 58 cancelRefresh(ex); 59 60 // Propagate exception to caller. 61 throw ex; 62 } 63 64 finally { 65 // Reset common introspection caches in Spring's core, since we 66 // might not ever need metadata for singleton beans anymore... 67 resetCommonCaches(); 68 } 69 } 70 }
2、在refresh().obtainFreshBeanFactory()
beandefinition 初始化, 把class存放在 beandefinitionMap中
@Override protected final void refreshBeanFactory() throws BeansException { if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); this.beanFactory = beanFactory; } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
3、在refresh().prepareBeanFactory()
// 准备在此上下文中使用的 bean 工厂.
// 3、初始化registerSingleton 格式化工厂、比如把系统的单例bean 添加到 单例缓存池中
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // Tell the internal bean factory to use the context's class loader etc. beanFactory.setBeanClassLoader(getClassLoader()); beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // Configure the bean factory with context callbacks. beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); // BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); // Register early post-processor for detecting inner beans as ApplicationListeners. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // Detect a LoadTimeWeaver and prepare for weaving, if found. if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } // Register default environment beans. if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
4、refresh().postProcessBeanFactory() 注册特殊的beanPostprecessor
// 4、在标准初始化之后修改应用程序上下文的内部 bean 工厂。 所有 bean 定义都将被加载,但尚未实例化任何 bean。
// 这允许在某些 ApplicationContext 实现中注册特殊的 BeanPostProcessor 等
1 protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { 2 // Tell the internal bean factory to use the context's class loader etc. 3 beanFactory.setBeanClassLoader(getClassLoader()); 4 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); 5 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); 6 7 // Configure the bean factory with context callbacks. 8 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); 9 beanFactory.ignoreDependencyInterface(EnvironmentAware.class); 10 beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); 11 beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); 12 beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); 13 beanFactory.ignoreDependencyInterface(MessageSourceAware.class); 14 beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); 15 16 // BeanFactory interface not registered as resolvable type in a plain factory. 17 // MessageSource registered (and found for autowiring) as a bean. 18 beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); 19 beanFactory.registerResolvableDependency(ResourceLoader.class, this); 20 beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); 21 beanFactory.registerResolvableDependency(ApplicationContext.class, this); 22 23 // Register early post-processor for detecting inner beans as ApplicationListeners. 24 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); 25 26 // Detect a LoadTimeWeaver and prepare for weaving, if found. 27 if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { 28 beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); 29 // Set a temporary ClassLoader for type matching. 30 beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); 31 } 32 33 // Register default environment beans. 34 if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { 35 beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); 36 } 37 if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { 38 beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); 39 } 40 if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { 41 beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); 42 } 43 }
5、refresh().invokeBeanFactoryPostProcessors() 注册特殊的beanPostprecessor
// 调用在上下文中注册为 bean 的工厂处理器
// 实例化并调用所有已注册的 BeanFactoryPostProcessor bean,如果给出,则遵守显式顺序。
// 必须在单例实例化之前调用
1 protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { 2 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); 3 4 // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime 5 // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) 6 if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { 7 beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); 8 beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); 9 } 10 }
6、refresh().registerBeanPostProcessors()
注册拦截 bean 创建的 bean处理器,把增强器postProcessor实例化和初始化
1 public static void registerBeanPostProcessors( 2 ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { 3 4 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); 5 6 // Register BeanPostProcessorChecker that logs an info message when 7 // a bean is created during BeanPostProcessor instantiation, i.e. when 8 // a bean is not eligible for getting processed by all BeanPostProcessors. 9 int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; 10 beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); 11 12 // Separate between BeanPostProcessors that implement PriorityOrdered, 13 // Ordered, and the rest. 14 List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); 15 List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); 16 List<String> orderedPostProcessorNames = new ArrayList<>(); 17 List<String> nonOrderedPostProcessorNames = new ArrayList<>(); 18 for (String ppName : postProcessorNames) { 19 if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { 20 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); 21 priorityOrderedPostProcessors.add(pp); 22 if (pp instanceof MergedBeanDefinitionPostProcessor) { 23 internalPostProcessors.add(pp); 24 } 25 } 26 else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { 27 orderedPostProcessorNames.add(ppName); 28 } 29 else { 30 nonOrderedPostProcessorNames.add(ppName); 31 } 32 } 33 34 // 首先,注册实现 PriorityOrdered 的 BeanPostProcessors。 35 // First, register the BeanPostProcessors that implement PriorityOrdered. 36 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); 37 registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); 38 39 // 接下来,注册实现 Ordered 的 BeanPostProcessors。 40 // Next, register the BeanPostProcessors that implement Ordered. 41 List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(); 42 for (String ppName : orderedPostProcessorNames) { 43 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); 44 orderedPostProcessors.add(pp); 45 if (pp instanceof MergedBeanDefinitionPostProcessor) { 46 internalPostProcessors.add(pp); 47 } 48 } 49 sortPostProcessors(orderedPostProcessors, beanFactory); 50 registerBeanPostProcessors(beanFactory, orderedPostProcessors); 51 52 // 现在,注册所有常规 BeanPostProcessor。 53 // Now, register all regular BeanPostProcessors. 54 List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(); 55 for (String ppName : nonOrderedPostProcessorNames) { 56 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); 57 nonOrderedPostProcessors.add(pp); 58 if (pp instanceof MergedBeanDefinitionPostProcessor) { 59 internalPostProcessors.add(pp); 60 } 61 } 62 registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); 63 64 // 最后,重新注册所有内部 BeanPostProcessor 65 // Finally, re-register all internal BeanPostProcessors. 66 sortPostProcessors(internalPostProcessors, beanFactory); 67 registerBeanPostProcessors(beanFactory, internalPostProcessors); 68 69 // Re-register post-processor for detecting inner beans as ApplicationListeners, 70 // moving it to the end of the processor chain (for picking up proxies etc). 71 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); 72 }
7、 refresh().initMessageSource() 国际化
8、 refresh().initApplicationEventMulticaster() 为此上下文初始化事件多播器。
9、 refresh().onRefresh() 可以覆盖的模板方法以添加特定于上下文的刷新工作。 在单例实例化之前调用特殊 bean 的初始化。这个实现是空的
10、 refresh().registerListeners() 添加实现 ApplicationListener 作为侦听器的 bean。 不影响其他监听器,可以不加bean。
11、refresh().finishBeanFactoryInitialization() 实例化、初始化非懒加载的bean
在DefaultListableBeanFactory类中执行方法
1 @Override 2 public void preInstantiateSingletons() throws BeansException { 3 if (logger.isTraceEnabled()) { 4 logger.trace("Pre-instantiating singletons in " + this); 5 } 6 7 // Iterate over a copy to allow for init methods which in turn register new bean definitions. 8 // While this may not be part of the regular factory bootstrap, it does otherwise work fine. 9 List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); 10 11 // Trigger initialization of all non-lazy singleton beans... 12 // 遍历bean 13 for (String beanName : beanNames) { 14 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); 15 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { 16 if (isFactoryBean(beanName)) { 17 Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); 18 if (bean instanceof FactoryBean) { 19 FactoryBean<?> factory = (FactoryBean<?>) bean; 20 boolean isEagerInit; 21 if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { 22 isEagerInit = AccessController.doPrivileged( 23 (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit, 24 getAccessControlContext()); 25 } 26 else { 27 isEagerInit = (factory instanceof SmartFactoryBean && 28 ((SmartFactoryBean<?>) factory).isEagerInit()); 29 } 30 if (isEagerInit) { 31 getBean(beanName); 32 } 33 } 34 } 35 else { 36 // 正式处理的方法 37 getBean(beanName); 38 } 39 } 40 } 41 42 // Trigger post-initialization callback for all applicable beans... 43 for (String beanName : beanNames) { 44 Object singletonInstance = getSingleton(beanName); 45 if (singletonInstance instanceof SmartInitializingSingleton) { 46 SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; 47 if (System.getSecurityManager() != null) { 48 AccessController.doPrivileged((PrivilegedAction<Object>) () -> { 49 smartSingleton.afterSingletonsInstantiated(); 50 return null; 51 }, getAccessControlContext()); 52 } 53 else { 54 smartSingleton.afterSingletonsInstantiated(); 55 } 56 } 57 } 58 }
非常中要doGetBean()方法,其中初始化、实例化
protected <T> T doGetBean( String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException { String beanName = transformedBeanName(name); Object bean; // 【三级缓存,解决循环依赖重点】手动检查是否有缓存 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 = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // Check if bean definition exists in this factory. 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); } else if (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else if (requiredType != null) { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } else { return (T) parentBeanFactory.getBean(nameToLookup); } } if (!typeCheckOnly) { markBeanAsCreated(beanName); } try { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } registerDependentBean(dep, beanName); try { getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } } // Create bean instance. if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { // 创建bean return createBean(beanName, mbd, args); } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean. destroySingleton(beanName); throw ex; } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName); prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { String scopeName = mbd.getScope(); if (!StringUtils.hasLength(scopeName)) { throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'"); } Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { 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); } } } catch (BeansException ex) { cleanupAfterBeanCreationFailure(beanName); throw ex; } } // Check if required type matches the type of the actual bean instance. if (requiredType != null && !requiredType.isInstance(bean)) { try { T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType); if (convertedBean == null) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } return convertedBean; } catch (TypeMismatchException ex) { if (logger.isTraceEnabled()) { logger.trace("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }
其中一个doGetBean是创建对象
// 调用实例化 before BeforeInstantiation 有机会返回一个代理而不是目标 bean 实例,
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
1 protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) 2 throws BeanCreationException { 3 4 if (logger.isTraceEnabled()) { 5 logger.trace("Creating instance of bean '" + beanName + "'"); 6 } 7 RootBeanDefinition mbdToUse = mbd; 8 9 // Make sure bean class is actually resolved at this point, and 10 // clone the bean definition in case of a dynamically resolved Class 11 // which cannot be stored in the shared merged bean definition. 12 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); 13 if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { 14 mbdToUse = new RootBeanDefinition(mbd); 15 mbdToUse.setBeanClass(resolvedClass); 16 } 17 18 // Prepare method overrides. 19 try { 20 mbdToUse.prepareMethodOverrides(); 21 } 22 catch (BeanDefinitionValidationException ex) { 23 throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), 24 beanName, "Validation of method overrides failed", ex); 25 } 26 27 try { 28 // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. 29 // 调用实例化 before BeforeInstantiation 有机会返回一个代理而不是目标 bean 实例, 30 Object bean = resolveBeforeInstantiation(beanName, mbdToUse); 31 if (bean != null) { 32 return bean; 33 } 34 } 35 catch (Throwable ex) { 36 throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, 37 "BeanPostProcessor before instantiation of bean failed", ex); 38 } 39 40 try { 41 // 干活的地方,创建bean 42 Object beanInstance = doCreateBean(beanName, mbdToUse, args); 43 if (logger.isTraceEnabled()) { 44 logger.trace("Finished creating instance of bean '" + beanName + "'"); 45 } 46 return beanInstance; 47 } 48 catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { 49 // A previously detected exception with proper bean creation context already, 50 // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry. 51 throw ex; 52 } 53 catch (Throwable ex) { 54 throw new BeanCreationException( 55 mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); 56 } 57 }
【重点】getSingleton()方法优雅解决循环依赖
1 protected Object getSingleton(String beanName, boolean allowEarlyReference) { 2 // Quick check for existing instance without full singleton lock 3 /** 4 * singletonObjects:一级缓存,单例池 5 * earlySingletonObjects:二级缓存,bean的半成品,解决性能问题,防止重复创建相同的bean 6 * singletonFactories:三级缓存,bean的工厂,生产bean,处理循环依赖,对外提前暴露,然后公共工厂获取bean 7 **/ 8 Object singletonObject = this.singletonObjects.get(beanName); 9 if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { 10 singletonObject = this.earlySingletonObjects.get(beanName); 11 if (singletonObject == null && allowEarlyReference) { 12 synchronized (this.singletonObjects) { 13 // Consistent creation of early reference within full singleton lock 14 singletonObject = this.singletonObjects.get(beanName); 15 if (singletonObject == null) { 16 singletonObject = this.earlySingletonObjects.get(beanName); 17 if (singletonObject == null) { 18 ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); 19 if (singletonFactory != null) { 20 singletonObject = singletonFactory.getObject(); 21 this.earlySingletonObjects.put(beanName, singletonObject); 22 this.singletonFactories.remove(beanName); 23 } 24 } 25 } 26 } 27 } 28 } 29 return singletonObject; 30 }
真正干活的doGetBean地方,包含创建、填充、初始化
1 protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) 2 throws BeanCreationException { 3 4 // Instantiate the bean. 5 BeanWrapper instanceWrapper = null; 6 if (mbd.isSingleton()) { 7 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); 8 } 9 if (instanceWrapper == null) { 10 // 实例化 创建bean ,并调用构造方法 11 instanceWrapper = createBeanInstance(beanName, mbd, args); 12 } 13 Object bean = instanceWrapper.getWrappedInstance(); 14 Class<?> beanType = instanceWrapper.getWrappedClass(); 15 if (beanType != NullBean.class) { 16 mbd.resolvedTargetType = beanType; 17 } 18 19 // Allow post-processors to modify the merged bean definition. 20 synchronized (mbd.postProcessingLock) { 21 if (!mbd.postProcessed) { 22 try { 23 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 24 } 25 catch (Throwable ex) { 26 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 27 "Post-processing of merged bean definition failed", ex); 28 } 29 mbd.postProcessed = true; 30 } 31 } 32 33 // Eagerly cache singletons to be able to resolve circular references 34 // even when triggered by lifecycle interfaces like BeanFactoryAware. 35 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && 36 isSingletonCurrentlyInCreation(beanName)); 37 if (earlySingletonExposure) { 38 if (logger.isTraceEnabled()) { 39 logger.trace("Eagerly caching bean '" + beanName + 40 "' to allow for resolving potential circular references"); 41 } 42 // 【重点】先实例化bean,在放入三级缓存中singletonFactories,提前暴露 ,目的为了不用重复创建bean,放在工厂方便bean的扩展 43 addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); 44 } 45 46 // Initialize the bean instance. 47 Object exposedObject = bean; 48 try { 49 // 【重点】 填充属性 50 populateBean(beanName, mbd, instanceWrapper); 51 // 【重点】初始化bean 52 // 增强器的使用before after,其中aop代理对象在此其中一个增强器after中代理了 53 exposedObject = initializeBean(beanName, exposedObject, mbd); 54 } 55 catch (Throwable ex) { 56 if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { 57 throw (BeanCreationException) ex; 58 } 59 else { 60 throw new BeanCreationException( 61 mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); 62 } 63 } 64 65 if (earlySingletonExposure) { 66 Object earlySingletonReference = getSingleton(beanName, false); 67 if (earlySingletonReference != null) { 68 if (exposedObject == bean) { 69 exposedObject = earlySingletonReference; 70 } 71 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { 72 String[] dependentBeans = getDependentBeans(beanName); 73 Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); 74 for (String dependentBean : dependentBeans) { 75 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { 76 actualDependentBeans.add(dependentBean); 77 } 78 } 79 if (!actualDependentBeans.isEmpty()) { 80 throw new BeanCurrentlyInCreationException(beanName, 81 "Bean with name '" + beanName + "' has been injected into other beans [" + 82 StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + 83 "] in its raw version as part of a circular reference, but has eventually been " + 84 "wrapped. This means that said other beans do not use the final version of the " + 85 "bean. This is often the result of over-eager type matching - consider using " + 86 "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example."); 87 } 88 } 89 } 90 } 91 92 // Register bean as disposable. 93 try { 94 registerDisposableBeanIfNecessary(beanName, bean, mbd); 95 } 96 catch (BeanDefinitionValidationException ex) { 97 throw new BeanCreationException( 98 mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); 99 } 100 101 return exposedObject; 102 }
getCreateBean里面的三部曲
11.1、实例化 创建bean ,并调用构造方法
1 protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { 2 // Make sure bean class is actually resolved at this point. 3 Class<?> beanClass = resolveBeanClass(mbd, beanName); 4 5 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { 6 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 7 "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); 8 } 9 10 Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); 11 if (instanceSupplier != null) { 12 return obtainFromSupplier(instanceSupplier, beanName); 13 } 14 15 if (mbd.getFactoryMethodName() != null) { 16 return instantiateUsingFactoryMethod(beanName, mbd, args); 17 } 18 19 // Shortcut when re-creating the same bean... 20 boolean resolved = false; 21 boolean autowireNecessary = false; 22 if (args == null) { 23 synchronized (mbd.constructorArgumentLock) { 24 if (mbd.resolvedConstructorOrFactoryMethod != null) { 25 resolved = true; 26 autowireNecessary = mbd.constructorArgumentsResolved; 27 } 28 } 29 } 30 if (resolved) { 31 if (autowireNecessary) { 32 return autowireConstructor(beanName, mbd, null, null); 33 } 34 else { 35 return instantiateBean(beanName, mbd); 36 } 37 } 38 39 // Candidate constructors for autowiring? 40 Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); 41 if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || 42 mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { 43 return autowireConstructor(beanName, mbd, ctors, args); 44 } 45 46 // Preferred constructors for default construction? 47 ctors = mbd.getPreferredConstructors(); 48 if (ctors != null) { 49 return autowireConstructor(beanName, mbd, ctors, null); 50 } 51 52 // 实例化 53 return instantiateBean(beanName, mbd); 54 }
11.2、【解决循环依赖重点】先实例化bean,在放入三级缓存中singletonFactories,提前暴露 ,目的为了不用重复创建bean,放在工厂方便bean
1 protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) { 2 Assert.notNull(singletonFactory, "Singleton factory must not be null"); 3 synchronized (this.singletonObjects) { 4 if (!this.singletonObjects.containsKey(beanName)) { 5 this.singletonFactories.put(beanName, singletonFactory); 6 this.earlySingletonObjects.remove(beanName); 7 this.registeredSingletons.add(beanName); 8 } 9 } 10 }
11.3、bean填充属性
1 protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { 2 if (bw == null) { 3 if (mbd.hasPropertyValues()) { 4 throw new BeanCreationException( 5 mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); 6 } 7 else { 8 // Skip property population phase for null instance. 9 return; 10 } 11 } 12 13 // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the 14 // state of the bean before properties are set. This can be used, for example, 15 // to support styles of field injection. 16 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { 17 for (BeanPostProcessor bp : getBeanPostProcessors()) { 18 if (bp instanceof InstantiationAwareBeanPostProcessor) { 19 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; 20 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { 21 return; 22 } 23 } 24 } 25 } 26 27 PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); 28 29 int resolvedAutowireMode = mbd.getResolvedAutowireMode(); 30 if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { 31 MutablePropertyValues newPvs = new MutablePropertyValues(pvs); 32 // Add property values based on autowire by name if applicable. 33 if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { 34 autowireByName(beanName, mbd, bw, newPvs); 35 } 36 // Add property values based on autowire by type if applicable. 37 if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { 38 autowireByType(beanName, mbd, bw, newPvs); 39 } 40 pvs = newPvs; 41 } 42 43 boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); 44 boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); 45 46 PropertyDescriptor[] filteredPds = null; 47 if (hasInstAwareBpps) { 48 if (pvs == null) { 49 pvs = mbd.getPropertyValues(); 50 } 51 for (BeanPostProcessor bp : getBeanPostProcessors()) { 52 if (bp instanceof InstantiationAwareBeanPostProcessor) { 53 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; 54 PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); 55 if (pvsToUse == null) { 56 if (filteredPds == null) { 57 filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); 58 } 59 pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); 60 if (pvsToUse == null) { 61 return; 62 } 63 } 64 pvs = pvsToUse; 65 } 66 } 67 } 68 if (needsDepCheck) { 69 if (filteredPds == null) { 70 filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); 71 } 72 checkDependencies(beanName, mbd, filteredPds, pvs); 73 } 74 75 if (pvs != null) { 76 applyPropertyValues(beanName, mbd, bw, pvs); 77 } 78 }
11.4、initializeBean(beanName, exposedObject, mbd)初始化bean
增强器的使用before after,其中aop代理对象在此其中一个增强器after中代理了
1 protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) { 2 if (System.getSecurityManager() != null) { 3 AccessController.doPrivileged((PrivilegedAction<Object>) () -> { 4 invokeAwareMethods(beanName, bean); 5 return null; 6 }, getAccessControlContext()); 7 } 8 else { 9 invokeAwareMethods(beanName, bean); 10 } 11 12 // 初始化三部曲 before ,init ,after 13 // 1、执行增强器before 方法 BeforeInitialization 14 Object wrappedBean = bean; 15 if (mbd == null || !mbd.isSynthetic()) { 16 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); 17 } 18 19 try { 20 // 2、初始化 bean对象,包括postProcessor增强器(@PostConstruct在这里执行) 21 invokeInitMethods(beanName, wrappedBean, mbd); 22 } 23 catch (Throwable ex) { 24 throw new BeanCreationException( 25 (mbd != null ? mbd.getResourceDescription() : null), 26 beanName, "Invocation of init method failed", ex); 27 } 28 29 ///3、 执行增强器before 方法 AfterInitialization 30 // 其中AOP就是在这里给bean替换成代理对象 31 if (mbd == null || !mbd.isSynthetic()) { 32 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); 33 } 34 35 return wrappedBean; 36 }
1 @Override 2 public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) 3 throws BeansException { 4 5 Object result = existingBean; 6 7 // 遍历增强器,其中一个AnnotationAwareAspectJAutoProxyCreator 是AOP代理增强器,在after中把bean替换成代理对象 8 for (BeanPostProcessor processor : getBeanPostProcessors()) { 9 Object current = processor.postProcessAfterInitialization(result, beanName); 10 if (current == null) { 11 return result; 12 } 13 result = current; 14 } 15 return result; 16 }
最后就是bean的销毁了