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