简体   繁体   English

@Repository中的Spring @PostConstruct函数被多次调用

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

I have a DAO that I'm trying to inject into a couple different places: 我有一个DAO,我想将其注入几个不同的地方:

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

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

And my application-context.xml is a fairly simple context:component-scan: 我的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>

The DAO is accessed from a couple servlets in my application server through @Autowired properties. 通过@Autowired属性从我的应用程序服务器中的几个servlet访问DAO。 As far as I understand, anything annotated with @Repository should default to being a singleton and thus doSomeDatabaseStuff() should only be called once (as is my intention). 据我了解,任何用@Repository注释的内容都应默认为单例,因此doSomeDatabaseStuff()仅应被调用一次(这是我的意图)。 The problem is that I'm seeing doSomeDatabaseStuff() called multiple times. 问题是我多次看到doSomeDatabaseStuff()。

What's going on here? 这里发生了什么? Have I set something up incorrectly? 我设置不正确吗? I'm using spring 3.0.0. 我正在使用spring 3.0.0。

Thanks for the help. 谢谢您的帮助。

UPDATE: I have a few servlets that all have the same xml config file shown above. 更新:我有几个servlet,它们都具有上面显示的相同的xml配置文件。 Will a new FooDAO instance get constructed for each servlet? 是否将为每个servlet构造一个新的FooDAO实例? If so, how do I prevent that from happening? 如果是这样,我如何防止这种情况发生?

I have a few servlets that all have the same xml config file shown above 我有几个servlet,它们都具有上面显示的相同的xml配置文件

this means you mean multiple spring contexts, and that in turn means that multiple instances are created (for each context). 这意味着您意味着多个spring上下文,而这又意味着(针对每个上下文)创建了多个实例。

You need only one spring context - ie only one xml config ( applicationContext.xml ) 需要一个 spring上下文-即只需要一个xml配置( applicationContext.xml

Read this tutorial to see how you should setup Spring MVC. 阅读本教程 ,了解如何设置Spring MVC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM