zoukankan      html  css  js  c++  java
  • Spring的bean作用域singleton prototype

    在spring中,组成应用的主体以及由Spring IoC容器所管理的对象称之为bean。换言之,bean就是由Spring容器初始化、装配及被管理的对象。
      
    singleton作用域:当Spring中一个bean的作用域为singleton时,那么Spring IoC容器中只会存在一个共享的该bean实例,并且所有对该bean的引用,只要id与该bean                            定期相匹配,则只会返回bean的单一实例。
    Spring容器的上下文中只有一个bean的实例对象,即容器的getBean()方法或将其注入到另一个bean中只能返回一个唯一的实例对象。在开发企业级的项目时经常需要singleton模式。在设置singleton作用域时,一下3中方式:
    <bean id="text" class="com.mommon.Text"/>
    <bean id="text" class="com.mommon.Text" singleton="true"/>
    <bean id="text" class="com.mommon.Text" scope="singleton"/>
     
    prototype作用域:prototpye作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者调用容器的getBean()方法)时都会创建一个新的bean实例。但是在prototpye作用域中当bean被容器创建完毕,并且将实例对象返回给请求方之后,容器就不再拥有当前返回的引用,容器将实例对象生命周期的管理工作交给请求方负责,所以在客户端代码中必须使用bean的后置处理器清除prototype作用域的bean,但是后置处理器持有要被清除的bean的引用。设置prototype作用域:<bean id="text" class="com.mommon.Text" singleton="false"/>
          <bean id="text" class="com.mommon.Text" scope="prototype"/>
     
    技巧:对所有有状态的bean应该使用prototype作用域,对无状态的bean使用singleton作用域
     
    注意:通常情况下,DAO不会被配置成prototype,因为一个典型的DAO不会持有任何回话状态,因此应该使用singleton作用域。
  • 相关阅读:
    pinpoint改造支持查询
    pinpoint本地开发——agent
    pinpoint本地开发——collector
    pinpoint本地开发-web模块
    第一个Vert.x程序
    ls bash: cannot create temp file for here-document: No space left on device
    hadoop磁盘空间不均衡的解决办法
    dubbo监控活跃线程数
    mac安装软件运行提示「xxx.app已损坏,打不开.你应该将它移到废纸篓」的解决办法
    python拆分excel脚本
  • 原文地址:https://www.cnblogs.com/xiaochaozi/p/3365047.html
Copyright © 2011-2022 走看看