当前位置 : 主页 > 编程语言 > java >

spring bean生命周期

来源:互联网 收集:自由互联 发布时间:2023-02-04
最近有幸接触了spring源码模块,正在做spring的源码翻译工作:简单从说一下 bean生命周期 顺便感谢领我入门的书,人,视频教程 关注下方的核心代码:populateBean(beanName, mbd, instanceWrapper);

最近有幸接触了spring源码模块,正在做spring的源码翻译工作:简单从说一下 bean生命周期

顺便感谢领我入门的书,人,视频教程

 

关注下方的核心代码:populateBean(beanName, mbd, instanceWrapper); // 初始化bean对象 exposedObject = initializeBean(beanName, exposedObject, mbd);这段spring代码也就是说明了spring是怎么创建bean后,注入值,回调各种回调接口 AUTOWIRE -> PostConstruct | aware-> BPPbefore -> afterPer-> init-method-> BPPafter

以 AnnotationConfigApplicationContext为例按照源码调用链执行讲解

第一步创建容器看refresh方法

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) { // 创建reader scanner beanfactory 注入七个PostProcessor this(); // 注册配置类到BeanDefinition register(annotatedClasses); // 启动容器 refresh();}

第二步看实例化单例的方法finishBeanFactoryInitialization

@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. // 获取beanfactory 也就是DefaultListableBeanFactory ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. // 2个beanPostProcesserr prepareBeanFactory(beanFactory); try { // 暂无实现,但是允许程序员继承后处理postProcessBeanFactory // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // 注册BeanFactoryPostProcessors并且完成bean和Import等的解析【ConfigurationClassPostProcessor】 // Invoke factory processors registered as beans in the context. // BeanFactoryPostProcessors核心处理 同时处理一个beanPostProcesserr /** * 这里有一个非常核心的类 * ConfigurationClassPostProcessor[BeanDefinitionRegistryPostProcessor]用来加载configuration component componentscan import importSelector等核心IOC过程 */ invokeBeanFactoryPostProcessors(beanFactory); // // Register bean processors that intercept bean creation. // 四个beanPostProcesserr 这些beanPostProcesserr 被建立成一个数组,放置在 // private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>(); registerBeanPostProcessors(beanFactory); // Initialize message source for this context. // 初始化messagesource initMessageSource(); // Initialize event multicaster for this context. // 初始化 事件广播 initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. // 暂无实现,可以自定义上下文用于扩展 onRefresh(); // Check for listener beans and register them. // 注册相关监听器 registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. // 创建BEAN实例,注意这里不处理原型bean,懒加载的bean等 finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }

在finishBeanFactoryInitialization时候看加载饥饿单例

// 饥饿加载所有的单例beanbeanFactory.preInstantiateSingletons();内部的if (isEagerInit) { // 默认是饥饿加载 getBean(beanName);}

沿着调用链向下看第一个AbstractBeanFactory核心方法getSingleton的【  return createBean(beanName, mbd, args);】

其实现交给AbstractAutowireCapableBeanFactory

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);}

========================================接下来就是核心=======================================

上面的代码只是链路的调用;不用关注具体

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException { /** * 有不同的方式创建bean * * 1 工厂创建 * 2 构造注入 * 3无参创建 */ // Instantiate the bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { instanceWrapper = createBeanInstance(beanName, mbd, args); } final Object bean = instanceWrapper.getWrappedInstance(); Class<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType; } // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } // Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isDebugEnabled()) { logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } // addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // Initialize the bean instance. Object exposedObject = bean; ///这里就是APAI的原因/ ///autowired postConstructor AfterP init-method// try { // 设置对象的属性 AUTOWIRE 处理PostConstruct // autowired -> postConstruct populateBean(beanName, mbd, instanceWrapper); // 初始化bean对象 aware-> before -> afterPer-> init-method-> after exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } } // Register bean as disposable. try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }

 

//autowired -> postConstructpopulateBean(beanName, mbd, instanceWrapper); // 初始化bean对象 aware-> before -> afterPer-> init-method-> afterexposedObject = initializeBean(beanName, exposedObject, mbd);这两段方法处理了各个生命周期的创建赋值1 populateBean 方法如下if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { /** * AutowiredAnnotationBeanPostProcessor 處理@Autowired * CommonAnnotationBeanPostProcessor 負責@Resource @PostConstruct @PreDestroy(交給父类和本身处理) */ InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } }这里也就是说明了@Autowired -》 @PostConstruct 2 protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareMethods(beanName, bean); return null; }, getAccessControlContext()); } else { // 什么是Aware spring的尿性是说我定义了一部分的Aware注入,当实现指定Aware接口,spring会将属于IOC容器内部的一些组件比如applicationContext等通过set方法赋值 invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { // PostProcessorsBefore BeanPostProcessors的前置处理 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { // InitializingBean afterPropertiesSet(); init-Method; // 这里调用afterPropertiesSet 以及bean 的 init-method invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || !mbd.isSynthetic()) { // BeanPostProcessorsAfter BeanPostProcessors的后置处理 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }最终也就是说:// 设置对象的属性 AUTOWIRE 处理PostConstruct // autowired -> postConstruct populateBean(beanName, mbd, instanceWrapper); // 初始化bean对象 aware-> before -> afterPer-> init-method-> after exposedObject = initializeBean(beanName, exposedObject, mbd);最后的destory这里不说

 

上一篇:Shell 变量知多少?
下一篇:没有了
网友评论