dublintech
dublintech

Reputation: 17785

Inject the same bean instance into two other beans

I wish to inject the same EntityManagerFactory instance into two of my spring beans.

I try:

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="my-app"/>   
</bean>      

<bean id="serverDAO"
    class="com.ehcachedemo.dao.ServerDAO">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<bean id="testServerDAO"
    class="com.ehcachedemo.test.TestServerDAO">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

But at runtime, two difference EntityManagerFactory instances are injected. Any tips? Thanks

Upvotes: 1

Views: 787

Answers (1)

Tim Pote
Tim Pote

Reputation: 28029

Considering the default spring-managed bean is a singleton, your entityManagerFactory bean should already be the same instance in both DAOs.

You can make this explicit by adding singleton="true" to your entityManagerFactory bean definition.

So your bean definition should be:

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"
    singleton="true">
    <property name="persistenceUnitName" value="my-app"/>   
</bean>

Upvotes: 1

Related Questions