Shawn
Shawn

Reputation: 7365

Reusing bean definitions in Spring

Our project has two application contexts:

Currently each file has duplicate bean definitions. So for example the following bean would be in each application context:

<bean id="foo "class="com.foo">
     <property name="bar">
          <ref local="bar"/>
     </property>
</bean>

The plan is to create another file for bean definitions so we can reuse the beans, however, if we put the above xml segment into its own file, there will be no reference to bar

Is there an easy way to solve this?

Please note that barwill be different in each application context.

Thanks!

Upvotes: 1

Views: 2082

Answers (2)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

Sure, use a common context file that you import into both xml files.

<import resource="/common"/>

See 4.2.2.1. Composing XML-based configuration metadata

Upvotes: 1

skaffman
skaffman

Reputation: 403441

<ref local="bar"/> has a specific meaning - it means that bar must be defined in the same file. In your case, that's too strict, so loosen it a bit:

<bean id="foo "class="com.foo">
     <property name="bar" ref="bar"/>
</bean>

And then use <import resource="..."> to import this file where needed.

With this, bar must still exist, but it can be in any file that's part of the context, or in any of the parent contexts.

Upvotes: 3

Related Questions