簡體   English   中英

@Repository中的Spring @PostConstruct函數被多次調用

[英]Spring @PostConstruct function in a @Repository called multiple times

我有一個DAO,我想將其注入幾個不同的地方:

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

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

我的application-context.xml是一個非常簡單的上下文:component-scan:

<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>

通過@Autowired屬性從我的應用程序服務器中的幾個servlet訪問DAO。 據我了解,任何用@Repository注釋的內容都應默認為單例,因此doSomeDatabaseStuff()僅應被調用一次(這是我的意圖)。 問題是我多次看到doSomeDatabaseStuff()。

這里發生了什么? 我設置不正確嗎? 我正在使用spring 3.0.0。

謝謝您的幫助。

更新:我有幾個servlet,它們都具有上面顯示的相同的xml配置文件。 是否將為每個servlet構造一個新的FooDAO實例? 如果是這樣,我如何防止這種情況發生?

我有幾個servlet,它們都具有上面顯示的相同的xml配置文件

這意味着您意味着多個spring上下文,而這又意味着(針對每個上下文)創建了多個實例。

需要一個 spring上下文-即只需要一個xml配置( applicationContext.xml

閱讀本教程 ,了解如何設置Spring MVC。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM