在看spring相關的文章時,通常都會說起spring默認建立的bean對象是單例的,可是在調試一個問題的時候發現並非這樣,即使是在類上聲明瞭@Singleton ,此時建立的對象也並不是是單例的。web
spring的單例是有前提條件的,即:在同一個container中是單例的。spring
而通常狀況下基於spring的web工程會建立2個container,一個是root container,即:root WebApplicationContext(日誌中會輸出此名稱);另外一個是servlet's context,即:以{web.xml中定義的DispatcherServlet}的名字命名的WebApplicationContext。express
以註解+xml的配置方式爲例子,須要讓servlet's context只掃描org.springframework.stereotype.Controller,而讓root container掃描除了org.springframework.stereotype.Controller以外的類,即:app
applicationContext.xml(多是其餘名字,僅示例)中配置爲:spa
<context:component-scan base-package="{略}"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
*-servlet.xml(多是其餘名字,僅示例)中配置爲:.net
<context:component-scan base-package="{略}" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
servlet's context會從root container中繼承service、dao等對象。調試
更豐富的信息,請參考一下頁面:
一、http://stackoverflow.com/questions/18578143/about-multiple-containers-in-spring-framework日誌