我有我試圖注入了幾個不同的地方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實例嗎?如果是這樣,我如何防止這種情況發生?
你可以在doSomeDatabaseStuff()中放一個斷點並檢查堆棧跟蹤嗎?這可能會幫助您找出它從哪裏被調用。可能很難理解所有的春天的東西,但它可能是照亮。 – John 2010-04-10 01:44:37
@John:它看起來像是從幾個不同的地方調用的,其中只有一個是我的一個servlet的init函數。 – Seth 2010-04-10 02:32:50
您也可以查看'this'的值來查看它是否真的是同一個對象,或者是否創建了多個實例。 – John 2010-04-10 02:35:45