【问题标题】:Spring @PostConstruct function in a @Repository called multiple times多次调用@Repository 中的Spring @PostConstruct 函数
【发布时间】:2010-04-09 22:59:09
【问题描述】:

我有一个 DAO,我正试图将其注入几个不同的地方:

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

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

而我的 application-context.xml 是一个相当简单的 context: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 实例?如果是这样,我该如何防止这种情况发生?

【问题讨论】:

  • 你能在 doSomeDatabaseStuff() 中放一个断点并检查堆栈跟踪吗?这可能会帮助您找出调用它的位置。理解所有春天的东西可能太难了,但它可能很有启发性。
  • @John:看起来它是从几个不同的地方调用的,其中只有一个是我的一个 servlet 的 init 函数。
  • 您还可以查看this 的值,看看它是否真的是同一个对象,或者是否正在创建多个实例。
  • 调试器显示不同的id,所以看起来像是不同的实例。

标签: java spring dependency-injection


【解决方案1】:

我有几个 servlet,它们都具有上面显示的相同 xml 配置文件

这意味着您的意思是多个 spring 上下文,而这反过来意味着创建了多个实例(对于每个上下文)。

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

阅读this tutorial 了解应该如何设置 Spring MVC。

【讨论】:

  • 我真的不明白该怎么做。我不是必须在每个 servlet 的 WEB-INF/ 中有一个 [servlet-name]-servlet.xml 吗?我怎样才能让他们都使用相同的豆子?
猜你喜欢
  • 2013-05-23
  • 2016-09-29
  • 2020-06-06
  • 2017-02-15
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 2012-12-18
相关资源
最近更新 更多