views:

46

answers:

3

If the president changes, I would have to change the value of presidentName three times below in the application-context.xml:

<beans:property name="presidentName" value="Barack Obama" />

Is there a way to set variable once in application-context.xml to represent the string Barack Obama.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.0.xsd"&gt;



    <beans:bean id="testBeanA" class="com.TestBean">
        <beans:property name="presidentName" value="Barack Obama" />
    </beans:bean>

    <beans:bean id="testBeanB" class="com.TestBean">
        <beans:property name="presidentName" value="Barack Obama" />
    </beans:bean>

    <beans:bean id="testBeanC" class="com.TestBean">
        <beans:property name="presidentName" value="Barack Obama" />
    </beans:bean>



</beans:beans>
+1  A: 

Define a bean specifying it as abstract (abstract="true") in spring and inject the presidentName property there. You can then define the 3 concrete beans by specifying the abstract bean you defined earlier as the parent. for e.g.

<beans:bean id="testBeanSpec" class="com.TestBean" abstract="true">
        <beans:property name="presidentName" value="Barack Obama" />
</beans:bean

<beans:bean id="testBeanA" class="com.TestBean" parent="testBeanSpec">
    </beans:bean
Pangea
+1  A: 

Define president as String-classed bean?

yawn
+1  A: 

As yawn pointed out you can define a new String-classed spring bean.

<bean id="testBeanA" class="com.TestBean">
    <property name="presidentName" ref="potus" />
</bean>

<bean name="potus" class="java.lang.String">
    <constructor-arg value="Barack Obama" />
</bean>
amphied