简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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