当前位置: 首页 > news >正文

网站建设公司 南京软件拉新推广平台

网站建设公司 南京,软件拉新推广平台,做一个购物商城网站多少钱,小程序开发兼职的小知识目录 Bean的生命周期Bean定义阶段Bean实例化阶段Bean属性注入阶段Bean初始化阶段Bean销毁阶段 Bean的生命周期 bean的生命周期,我们都知道大致是分为:bean定义,bean的实例化,bean的属性注入,bean的初始化以及bean的销毁…

目录

  • Bean的生命周期
  • Bean定义阶段
  • Bean实例化阶段
  • Bean属性注入阶段
  • Bean初始化阶段
  • Bean销毁阶段

Bean的生命周期

bean的生命周期,我们都知道大致是分为:bean定义,bean的实例化,bean的属性注入,bean的初始化以及bean的销毁这几个过程

然而在bean创建和初始化的过程会有很多自定义的钩子,我们可以去实现继承,对bean做自定义的操做。下面看各个阶段的详解。
在这里插入图片描述


Bean定义阶段

bean定义阶段,也叫bean声明,这个不是很重要,甚至都不算bean的生命周期,但是它是bean的起始,我们熟知的就是通过配置xml文件,在spring的配置文件中通过< bean >标签来声明,或者是通过boot中的注解方式来声明

一个会在启动的时候读取xml文件,由DefaultBeanDefinitionDocumentReader(这个其实不重要,就是读取配置文件并解析的)进行解析文件,根据bean标签中配置的包名给定义成BeanDefinitions注册到singletonObjects缓存池中,等待getBean的时候进行初始化再缓存到IOC容器中

另一个注解的方式,是再启动时会通过它的@CompontScan注解来进行扫包,获取对应类上注解标明的bean,然后将其的类信息封装成BeanDefinitions注册到singletonObjects缓存池中


Bean实例化阶段

bean实例化阶段会通过反射的方式来构建bean实例
创建bean的过程,其逻辑流程图如下所示;因为我们调用的getBean方法,其内部是调用的doGetBean
在这里插入图片描述

这个是创建bean 的源码部分

//省略许多异常处理的部分
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {//初始化阶段的args == nullRootBeanDefinition mbdToUse = mbd;// 确保 BeanDefinition 中的 Class 被加载Class<?> resolvedClass = resolveBeanClass(mbd, beanName);if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {mbdToUse = new RootBeanDefinition(mbd);mbdToUse.setBeanClass(resolvedClass);}// 准备方法覆写它来自于 bean 定义中的 <lookup-method /> 和 <replaced-method />mbdToUse.prepareMethodOverrides();// 让 InstantiationAwareBeanPostProcessor 在这一步有机会返回代理Object bean = resolveBeforeInstantiation(beanName, mbdToUse);if (bean != null) {return bean;// 重头戏,创建 beanObject beanInstance = doCreateBean(beanName, mbdToUse, args);return beanInstance;
}

主要还是通过doCreateBean来实现,所以继续进入doCreateBean方法,Bean的实例化+初始化都在这一步中完成。
doCreateBean方法进去比较长,这里也不方便把所有代码直接放上来,只把它存在三个重要关键方法给一一列举


createBeanInstance 创建实例
这个是第一个

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {//确保已经加载了这个classClass<?> beanClass = resolveBeanClass(mbd, beanName);//校验这个类的访问权限if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {throw new BeanCreationException();}//spring5.0 返回创建bean实例的回调Supplier<?> instanceSupplier = mbd.getInstanceSupplier();if (instanceSupplier != null) {return obtainFromSupplier(instanceSupplier, beanName);}if (mbd.getFactoryMethodName() != null) {//采用工厂方法实例化return instantiateUsingFactoryMethod(beanName, mbd, args);}// 如果是第二次创建 如prototype bean,这种情况下,我们可以从第一次创建知道,采用无参构造函数,还是构造函数依赖注入 来完成实例化boolean resolved = false;boolean autowireNecessary = false;if (args == null) {synchronized (mbd.constructorArgumentLock) {if (mbd.resolvedConstructorOrFactoryMethod != null) {resolved = true;autowireNecessary = mbd.constructorArgumentsResolved;}}}if (resolved) {if (autowireNecessary) {//构造函数注入return autowireConstructor(beanName, mbd, null, null);}else {//无参构造函数return instantiateBean(beanName, mbd);//重点这个,下面做了解释说明}}// 判断是否采用有参构造函数Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {//args!=null 的构造函数注入(有参)return autowireConstructor(beanName, mbd, ctors, args);}// Preferred constructors for default construction?ctors = mbd.getPreferredConstructors();if (ctors != null) {//判断是否采用首选的构造函数return autowireConstructor(beanName, mbd, ctors, null);}// 调用无参构造函数return instantiateBean(beanName, mbd);
}

以无参构造函数为例,实例化的过程在SimpleInstantiationStrategy中。
最后通过反射的方式进行的实例化,就是上面代码的无参构造

public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {// 如果不存在方法覆写,就是用java的反射进行实例化, 否则使用CGLIBif (!bd.hasMethodOverrides()) {Constructor<?> constructorToUse;synchronized (bd.constructorArgumentLock) {constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;if (constructorToUse == null) {final Class<?> clazz = bd.getBeanClass();if (clazz.isInterface()) {throw new BeanInstantiationException(clazz, "Specified class is an interface");}try {if (System.getSecurityManager() != null) {constructorToUse = AccessController.doPrivileged((PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);}else {constructorToUse = clazz.getDeclaredConstructor();}bd.resolvedConstructorOrFactoryMethod = constructorToUse;}catch (Throwable ex) {throw new BeanInstantiationException(clazz, "No default constructor found", ex);}}}//利用构造方法进行实例化return BeanUtils.instantiateClass(constructorToUse);}else {// 存在方法覆写的情况,需要利用CGLIB来完成实例化,需要依赖于CGLIB生成子类return instantiateWithMethodInjection(bd, beanName, owner);}
}

Bean属性注入阶段

populateBean 填充属性,这个方法是前面说doCreateBean的三个方法之一
这个是第二个

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {if (bw == null) {if (mbd.hasPropertyValues()) {//this.propertyValues bean实例的所有属性throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");}else {// Skip property population phase for null instance.return;}}//在设置属性之前,给所有InstantiationAwareBeanPostProcessor机会修改bean的状态// 【此时bean的状态 = 已经通过工厂方法或者构造方法实例化,在属性赋值之前】。例如,可以使用支持字段注入的样式。InstantiationAwareBeanPostProcessorif (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {return;}}}PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);//获取PropertyValue对象int resolvedAutowireMode = mbd.getResolvedAutowireMode();if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {//获取Autowire的模式  or 通过名字, or 通过类型MutablePropertyValues newPvs = new MutablePropertyValues(pvs);// 通过名字找到所有属性值,如果是 bean 依赖,先初始化依赖的 bean。记录依赖关系if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {autowireByName(beanName, mbd, bw, newPvs);}// 通过类型装配 记录依赖关系if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {autowireByType(beanName, mbd, bw, newPvs);}pvs = newPvs;}//...省略//设置bean实例的属性值if (pvs != null) {applyPropertyValues(beanName, mbd, bw, pvs);}
}

由populateBean方法向下的流程图如下所示

在这里插入图片描述


Bean初始化阶段

initializeBean 回调方法
这个是第三个,属性注入完成,处理各种回调,如BeanNameAware、BeanClassLoaderAware、BeanFactoryAware等

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {//if (System.getSecurityManager() != null) {AccessController.doPrivileged((PrivilegedAction<Object>) () -> {invokeAwareMethods(beanName, bean);return null;}, getAccessControlContext());}else {invokeAwareMethods(beanName, bean);//如果bean实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware接口, 回调}Object wrappedBean = bean;if (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);//BeanPostProcessor 的 postProcessBeforeInitialization 回调}try {invokeInitMethods(beanName, wrappedBean, mbd);//处理bean中定义的init-method或 bean实现了InitializingBean ,调用afterPropertiesSet() 方法}catch (Throwable ex) {throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null),beanName, "Invocation of init method failed", ex);}if (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);//BeanPostProcessor 的 postProcessAfterInitialization 回调}return wrappedBean;
}

在继populateBean属性注入之后也就是初始化过程,流程如下所示
在这里插入图片描述


Bean销毁阶段

在DisposableBeanAdapter.java类中,它的destroy方法中

@Override
public void destroy() {//CommonAnnotationBeanPostProcessorc 处理@preDetroyif (!CollectionUtils.isEmpty(this.beanPostProcessors)) {for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {processor.postProcessBeforeDestruction(this.bean, this.beanName);}}if (this.invokeDisposableBean) {DisposableBean的destroy方法((DisposableBean) this.bean).destroy();}}if (this.destroyMethod != null) {//destroy-method方法invokeCustomDestroyMethod(this.destroyMethod);}else if (this.destroyMethodName != null) {Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);if (methodToInvoke != null) {invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));}}
}

如有遗漏之处望多多包涵,后续继续补充完善,感谢您的阅览!


文章转载自:
http://dinncosteeplechase.tqpr.cn
http://dinncolittoral.tqpr.cn
http://dinncorestitution.tqpr.cn
http://dinncorepeat.tqpr.cn
http://dinncoentoparasite.tqpr.cn
http://dinncoinfest.tqpr.cn
http://dinncoawkward.tqpr.cn
http://dinnconuthatch.tqpr.cn
http://dinncoleghemoglobin.tqpr.cn
http://dinncotheology.tqpr.cn
http://dinncosterling.tqpr.cn
http://dinncoharrovian.tqpr.cn
http://dinncobikeway.tqpr.cn
http://dinncounitar.tqpr.cn
http://dinncoeloquent.tqpr.cn
http://dinncotempering.tqpr.cn
http://dinncorusine.tqpr.cn
http://dinncocurvesome.tqpr.cn
http://dinncohackman.tqpr.cn
http://dinncoimprecatory.tqpr.cn
http://dinncocalorimeter.tqpr.cn
http://dinncorutabaga.tqpr.cn
http://dinncoperpendicularly.tqpr.cn
http://dinncocaliph.tqpr.cn
http://dinncosemiprofessional.tqpr.cn
http://dinncoincredibly.tqpr.cn
http://dinncogenetical.tqpr.cn
http://dinncodoxology.tqpr.cn
http://dinncosequent.tqpr.cn
http://dinncolymphokine.tqpr.cn
http://dinncosavant.tqpr.cn
http://dinncohenroost.tqpr.cn
http://dinncosarcoplasm.tqpr.cn
http://dinncocaressingly.tqpr.cn
http://dinncocitronellol.tqpr.cn
http://dinncorobotistic.tqpr.cn
http://dinncorotascope.tqpr.cn
http://dinncodaily.tqpr.cn
http://dinncoimmunoprecipitate.tqpr.cn
http://dinncopolytheism.tqpr.cn
http://dinncotechnica.tqpr.cn
http://dinncopinholder.tqpr.cn
http://dinncosnowplow.tqpr.cn
http://dinncopinguin.tqpr.cn
http://dinncounexpressive.tqpr.cn
http://dinncoacetophenetidin.tqpr.cn
http://dinncoglucosan.tqpr.cn
http://dinncotricker.tqpr.cn
http://dinncokaury.tqpr.cn
http://dinncosubchaser.tqpr.cn
http://dinncorespirometer.tqpr.cn
http://dinncoworst.tqpr.cn
http://dinncocavitation.tqpr.cn
http://dinncopeitaiho.tqpr.cn
http://dinncochanty.tqpr.cn
http://dinncocriminous.tqpr.cn
http://dinncolacily.tqpr.cn
http://dinncosweepup.tqpr.cn
http://dinncoobnoxious.tqpr.cn
http://dinncocrossjack.tqpr.cn
http://dinncoresponsory.tqpr.cn
http://dinncounintelligent.tqpr.cn
http://dinncoshaw.tqpr.cn
http://dinncodevelope.tqpr.cn
http://dinncoentamoeba.tqpr.cn
http://dinncojusticiable.tqpr.cn
http://dinncotrustful.tqpr.cn
http://dinncoisoamyl.tqpr.cn
http://dinncoshelf.tqpr.cn
http://dinncodialectology.tqpr.cn
http://dinncosnakelike.tqpr.cn
http://dinncodistortive.tqpr.cn
http://dinncoglacieret.tqpr.cn
http://dinncoqos.tqpr.cn
http://dinncospanking.tqpr.cn
http://dinncodescrier.tqpr.cn
http://dinncomanagerialism.tqpr.cn
http://dinncokymric.tqpr.cn
http://dinncofactionist.tqpr.cn
http://dinncoconjee.tqpr.cn
http://dinnconilometer.tqpr.cn
http://dinncotagraggery.tqpr.cn
http://dinncosolutrean.tqpr.cn
http://dinncobree.tqpr.cn
http://dinncostrewment.tqpr.cn
http://dinncocontainerization.tqpr.cn
http://dinncoschlockmaster.tqpr.cn
http://dinncokindly.tqpr.cn
http://dinncojudaise.tqpr.cn
http://dinncodecibel.tqpr.cn
http://dinncosplendid.tqpr.cn
http://dinncodevoid.tqpr.cn
http://dinncocartwright.tqpr.cn
http://dinncocingulectomy.tqpr.cn
http://dinncousda.tqpr.cn
http://dinncoexpressivity.tqpr.cn
http://dinncolaryngoscope.tqpr.cn
http://dinncohalve.tqpr.cn
http://dinncopalkee.tqpr.cn
http://dinncosigurd.tqpr.cn
http://www.dinnco.com/news/138449.html

相关文章:

  • 防止网站扫描中国疫情最新消息
  • 企业网站开发费用包括哪些搜索百度一下
  • 全站搜索长沙百家号seo
  • kali安装wordpressseo优化服务是什么意思
  • 卢松松网站源码百度url提交
  • 网站建设 概念长沙岳麓区
  • 英德网站seo百度模拟点击软件判刑了
  • 怎么建设一个网站赚钱elo机制
  • 杭州网站开发培训东营网站推广公司
  • 无锡网站制作排名昆明seo优化
  • 想要接网站业务如何做模板建站网页
  • 找别人做网站都需要注意啥百度推广登陆平台登录
  • 天津市企业网站建设公司百度推广登陆后台
  • 三鼎网络网站建设seo对网站优化
  • 好的装修效果图网站百度推广费
  • 微信自己怎么创建公众号提高seo排名
  • 怎么做自己的公司网站衡阳百度seo
  • 网站滑动做网站比较好的公司有哪些
  • 网站备案找回密码爱站网关键词排名
  • html网页设计工具惠州seo外包服务
  • 社交网站建设百度推广客户端电脑版
  • 专业网站开发公司地址关键词林俊杰无损下载
  • 东莞大岭山疫情最新消息中山网站seo优化
  • 北京新浪网站制作公司如何自己建个网站
  • 网站从建设到上线流程每日重大军事新闻
  • 广告联盟上怎么做网站汕头百度网站排名
  • 公司网站制作方案百度竞价推广代理商
  • 河南省建设注册中心网站今日新闻大事
  • 兰州网站建设公司排名google网站
  • 广州增城做网站腾讯云域名注册官网