zoukankan      html  css  js  c++  java
  • spring中bean的scope属性理解

    bean的scope属性有prototype,singleton,request, session几个属性

    spring和struts2整合的时候,struts2的action要配置成scope="prototype",这是为了线程安全,

    下面是struts2+hibernate+spring配置文件的一部分,以前都是仿造已经写好的bean的配置。有一次 scope="prototype"忘记写了结果出了问题 ,其默认是scope="singleton",唯一的。
          项目中对一个表的增删该操作是用一个action,这个action有add,update,delete,save这些方法,添加和修改是共用一个页面,当页面得到id时代表进行的修改操作,反之是添加操作。因为在配置spring的bean是忘了写scope="prototype"所以每次添加时都显示最后一次访问过的记录。
           找了很长时间,原来是spring bean出了问题。 scope="prototype" 会在该类型的对象被请求时创建一个新的action对象。如果没有配置scope=prototype则添加的时候不会新建一个action,他任然会保留上次访问的过记录的信息。 
    <bean id="assetAction" class="com.servicezone.itsd.asset.webapp.action.AssetAction" scope="prototype"> 

    既然action配置了scope="prototype",那么action里的bean就不能配置成scope="request"和scope="session",不然会报错:org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customer': Scope 'request' 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; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

    这也可以理解,action是每次都是新的,但是里面的属性却不是

  • 相关阅读:
    nginx 自启动脚本
    debian开机启动管理
    vagrant up connection time out
    vagrant在windows下的使用
    Office Web Apps Server
    邻接表模型中的节点移动
    Managing Hierarchical Data in MySQL(邻接表模型)[转载]
    play mp3 in c#
    2014年5月份第3周51Aspx源码发布详情
    2014年5月份第2周51Aspx源码发布详情
  • 原文地址:https://www.cnblogs.com/shamo89/p/6856447.html
Copyright © 2011-2022 走看看