spring 中scope的singleton和prototype區別

來源:互聯網
上載者:User

<bean id="meetAction" class="com.web.actions.MeetsAction"
  scope="prototype">
  <property name="meetsService" ref="meetsService" />
</bean>

       scope="prototype"沒寫的問題,項目中對一個表的增刪該操作是用一個action,這個actionadd,update,delete,save這些方法, 添加和修改是共用一個頁面,當頁面得到id時代表進行的修改操作,反之是添加操作。因為在配置spring的bean是忘了寫scope="prototype" 所以每次添加時都顯示最後一次訪問過的記錄,scope="prototype" 會在該類型的對象被請求 時建立一個新的action對象。如果沒有配置scope=prototype則添加的時候不會建立一個action,他任然會保留上次訪問的過記錄的資訊 webwork的Action不是安全執行緒的,要求在多線程環境下必須是一個線程對應一個獨立的執行個體,不能使用singleton。所以,我們在Spring配置Webwork Action Bean時,需要加上屬性scope=”prototype”或singleton=”false”。
      singleton模式指的是對某個對象的完全共用,包括代碼空間和資料空間,說白了,如果一個類是singleton的,假如這個類有成員變數,那麼這個成員變數的值是各個線程共用的(有點類似於static的樣子了),當線程A往給變數賦了一個值以後,線程B就能讀出這個值。因此,對於前台Action,肯定不能使用singleton的模式,必須是一個線程請求對應一個獨立的執行個體。推而廣之,只要是帶資料成員變數的類,為了防止多個線程混用資料,就不能使用singleton。對於我們用到的Service、Dao,之所以用了singleton,就是因為他們沒有用到資料成員變數,如果誰的Service需要資料成員變數,請設定singleton=false。 有狀態的bean都使用Prototype範圍,而對無狀態的bean則應該使用singleton範圍。

       在 Spring2.0中除了以前的Singleton和Prototype外又加入了三個新的web範圍,分別為request、session和 global session。如果你希望容器裡的某個bean擁有其中某種新的web範圍,除了在bean級上配置相應的scope屬性,還必須在容器級做一個額外的初始化配置。即在web應用的web.xml中增加這麼一個ContextListener: org.springframework.web.context.request.RequestContextListener 以上是針對Servlet 2.4以後的版本。比如Request範圍。

對於Spring 1.* & Spring 2.0配置有區別

Spring 1.*
<bean id="hibernateSessionFactory" class="org.hibernate.admin.component.HibernateSessionFactory" init-method="init" destroy-method="dispose" singleton="true">

Spring 2.0
spring-beans-2.0.dtd/xsd does not support singleton="true"/"false" anymore. Use scope="singleton/"prototype" instead!
<bean id="hibernateSessionFactory" class="org.hibernate.admin.component.HibernateSessionFactory" init-method="init" destroy-method="dispose" scope="singleton">

 

來源:http://aixiangct.blog.163.com/blog/static/9152246120103110436971/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.