在看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日志