`
javawangli
  • 浏览: 221502 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

一分钟掌握Spring 中bean 的生命周期!

阅读更多

 


  Spring bean 的生命周期短暂吗?

 

      spring中,从BeanFactoryApplicationContext取得的实例为Singleton,也就是预设为每一个Bean的别名只能维持一个实例,而不是每次都产生一个新的对象使用Singleton模式产生单一实例,对单线程的程序说并不会有什么问题,但对于多线程的程序,就必须注意安全(Thread-safe)的议题,防止多个线程
同时存取共享资源所引发的数据不同步问题。
然而在spring中 可以设定每次从BeanFactoryApplicationContext指定别名并取得Bean时都产生一个新的实例:例如:
<bean id="studentService" class="cn.csdn.service.StudentSrvice" singleton="false">
spring中,singleton属性默认是true,只有设定为false,则每次指定别名取得的Bean时都会产生一个新的实例

一个Bean从创建到销毁,如果是用BeanFactory来生成,管理Bean的话,会经历几个执行阶段(如图1.1

     
    1Bean的建立:

      容器寻找Bean的定义信息并将其实例化。  

   2:属性注入:
          使用依赖注入,Spring按照Bean定义信息配置Bean所有属性
    3BeanNameAwaresetBeanName()
          如果Bean类有实现org.springframework.beans.BeanNameAware接口,工厂调用BeansetBeanName()方法传递BeanID

   4BeanFactoryAwaresetBeanFactory()
          如果Bean类有实现org.springframework.beans.factory.BeanFactoryAware接口,工厂调用setBeanFactory()方法传入工厂自身。
    5BeanPostProcessorsProcessBeforeInitialization()
          如果org.springframework.beans.factory.config.BeanPostProcessorsBean关联,那么其postProcessBeforeInitialization()方法将被将被调用。
    6initializingBeanafterPropertiesSet()
          如果Bean类已实现org.springframework.beans.factory.InitializingBean接口,则执行他的afterProPertiesSet()方法
    7Bean定义文件中定义init-method
          可以在Bean定义文件中使用"init-method"属性设定方法名称例如:
          <bean id="studentService" calss="cn.csdn.service.StudentService" init-method="init">
          如果有以上设置的话,则执行到这个阶段,就会执行initBean()方法
    8BeanPostProcessorsProcessaAfterInitialization()
          如果有任何的BeanPostProcessors实例与Bean实例关联,则执行BeanPostProcessors实例的ProcessaAfterInitialization()方法

此时,Bean已经可以被应用系统使用,并且将保留在BeanFactory中知道它不在被使用。有两种方法可以将其从BeanFactory中删除掉(如图1.2):

  
    1DisposableBeandestroy()
          在容器关闭时,如果Bean类有实现org.springframework.beans.factory.DisposableBean接口,则执行他的destroy()方法
    2Bean定义文件中定义destroy-method
          在容器关闭时,可以在Bean定义文件中使用"destroy-method"属性设定方法名称,例如:
  <bean id="studentService" calss="cn.csdn.service.StudentService"destroy-method="destroy">
          如果有以上设定的话,则进行至这个阶段时,就会执行destroy()方法,如果是使用ApplicationContext来生成并管理Bean的话则稍有不同,使用ApplicationContext来生成及管理Bean实例的话,在执行BeanFactoryAwaresetBeanFactory()阶段后,若Bean类上有实现org.springframework.context.ApplicationContextAware接口,则执行其setApplicationContext()方法,接着才执行BeanPostProcessorsProcessBeforeInitialization()及之后的流程

 

<!--EndFragment-->

  • 大小: 126.5 KB
  • 大小: 147.2 KB
2
4
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics