在@Repository春@PostConstruct函数调用多次

问题描述:

我有我试图注入了几个不同的地方DAO:在@Repository春@PostConstruct函数调用多次

@Repository 
public class FooDAO 
{ 
    @Autowired 
    private HibernateManager sessionFactory; 

    @PostConstruct 
    public void doSomeDatabaseStuff() throws DataAccessException 
    { 
     ... 
    } 
} 

我的应用程序的context.xml是一个相当简单的背景:组件扫描:

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-init-method="init" default-destroy-method="destroy"> 

    <context:component-scan base-package="top.level"/> 
</beans> 

DAO是通过@Autowired属性从我的应用程序服务器中的一对servlet访问的。据我了解,任何使用@Repository注释的应该默认为单例,因此doSomeDatabaseStuff()应该只被调用一次(正如我的意图)。问题是我看到多次调用doSomeDatabaseStuff()。

这是怎么回事?我有不正确的东西吗?我使用的是spring 3.0.0。

感谢您的帮助。

更新:我有几个servlet都具有上面显示的相同的xml配置文件。会为每个servlet构建一个新的FooDAO实例吗?如果是这样,我如何防止这种情况发生?

+0

你可以在doSomeDatabaseStuff()中放一个断点并检查堆栈跟踪吗?这可能会帮助您找出它从哪里被调用。可能很难理解所有的春天的东西,但它可能是照亮。 – John 2010-04-10 01:44:37

+0

@John:它看起来像是从几个不同的地方调用的,其中只有一个是我的一个servlet的init函数。 – Seth 2010-04-10 02:32:50

+0

您也可以查看'this'的值来查看它是否真的是同一个对象,或者是否创建了多个实例。 – John 2010-04-10 02:35:45

我有几个小服务程序,所有具有上述

,这意味着你的意思是多春上下文显示相同的XML配置文件,而这又意味着,多个实例被创建(为每个上下文) 。

需要只有一个 Spring上下文 - 即只有一个xml配置(applicationContext.xml

this tutorial怎么看,您应该设置Spring MVC的。

+0

我真的不明白该怎么做。我的WEB-INF/servlet中没有[servlet-name] -servlet.xml文件吗?我怎样才能让他们都使用相同的豆子? – Seth 2010-04-12 22:27:01