jammer
jammer

Reputation: 161

Refer a set of properties in a spring bean

I am using spring and having a requirement where I need to configure lots of beans. ex :

<bean name="PC_Name" class="com.stack.Exchange">
 <property name="firstName" value="jack"/>
 <property name="lastName"  value="nicolas"/>
</bean>

<bean name="Mobile_Name" class="com.stack.Exchange">
  <property name="firstName" value="jack"/>
  <property name="lastName"  value="nicolas"/>
</bean>

Now, as in both above beans I am using same properties and same values. Is there any way to write these properties in a common tag and inject that in above beans. some thing like :

<bean name="PC_Name" class"com.stack.Exchange">
  <properties name="nameReference"/> 
</bean>

<bean name="Mobile_Name" class"com.stack.Exchange">
 <properties name="nameReference"/> 
</bean> 

 <properties name="nameReference">
    <property name="firstName" value="jack"/>
    <property name="lastName"  value="nicolas"/>
 </properties> 

I know it can be achieved by Defining another class with firstName and lastName variables and inject that class in the required bean. But I do not want to change code which has been written already in com.stack.Exchange class.

Thanks Nitin

Upvotes: 1

Views: 88

Answers (1)

sven.kwiotek
sven.kwiotek

Reputation: 1479

You have the possibility to create a Bean definition template. In this bean you have to declare an attribute "abstract" with value true. You should not specify class attribute in it.

    <bean id="beanTemplate" abstract="true">
       <property name="firstName" value="jack"/>
       <property name="lastName"  value="nicolas"/>
    </bean>
    <bean name="PC_Name" class"com.stack.Exchange" parent="beanTemplate">
    </bean>
    <bean name="Mobile_Name" class"com.stack.Exchange" parent="beanTemplate">
    </bean>

Upvotes: 1

Related Questions