Reputation: 5738
I have a DAO that I'm trying to inject into a couple different places:
@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:
<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. 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). The problem is that I'm seeing doSomeDatabaseStuff() called multiple times.
What's going on here? Have I set something up incorrectly? I'm using spring 3.0.0.
Thanks for the help.
UPDATE: I have a few servlets that all have the same xml config file shown above. Will a new FooDAO instance get constructed for each servlet? If so, how do I prevent that from happening?
Upvotes: 1
Views: 3131
Reputation: 597344
I have a few servlets that all have the same xml config file shown above
this means you mean multiple spring contexts, and that in turn means that multiple instances are created (for each context).
You need only one spring context - i.e. only one xml config (applicationContext.xml
)
Read this tutorial to see how you should setup Spring MVC.
Upvotes: 1