在看spring相关的文章时,一般都会提及spring默认创建的bean对象是单例的,但是在调试一个问题的时候发现并不是这样,即便是在类上声明了@Singleton ,此时创建的对象也并非是单例的。
spring的单例是有前提条件的,即:在同一个container中是单例的。
而一般情况下基于spring的web工程会创建2个container,一个是root container,即:root WebApplicationContext(日志中会输出此名称);另一个是servlet's context,即:以{web.xml中定义的DispatcherServlet}的名字命名的WebApplicationContext。
以注解+xml的配置方式为例子,需要让servlet's context只扫描org.springframework.stereotype.Controller,而让root container扫描除了org.springframework.stereotype.Controller之外的类,即:
applicationContext.xml(可能是其他名字,仅示例)中配置为:
<context:component-scan base-package="{略}">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
*-servlet.xml(可能是其他名字,仅示例)中配置为:
<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等对象。
更丰富的信息,请参考一下页面:
1、http://stackoverflow.com/questions/18578143/about-multiple-containers-in-spring-framework