【发布时间】:2012-11-12 18:45:39
【问题描述】:
我有一个基于 Spring 的 WebApp。在我的应用程序上下文中,我定义了这个 bean:
<bean id="someSingleton" class="com.fake.SomeSingleton" scope="singleton"/>
我有一个 Spring 调度 servlet 定义和一个具有 @Controller 注释的类,我自动连接了这个 bean,期望 Spring 只实例化这个类一次。但是,根据下面的调试代码,Spring不止一次地实例化了这个类:
private static final Semaphore SANITY_CHECK = new Semaphore(1);
public FakeSingleton(){
if(!SANITY_CHECK.tryAcquire()){
log.error("why?");
System.exit(-1);
else{
log.error("OK");
}
}
可能是什么原因?
注意:我使用的是 spring 3.1.2.RELEASE
编辑:
感谢给我的提示,我找到了罪魁祸首。
除了 DispatcherServlet,我的 web.xml 中还有一个 ContextLoaderListener。删除后,SomeSingleton 只被实例化了一次。
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>FakeService</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
【问题讨论】:
标签: spring dependency-injection