如何在application-context.xml中设置局部变量来表示重复值?

kor*_*ors 5 java configuration spring spring-mvc spring-security

如果总统改变了,我将不得不在下面改变presidentName三次的价值application-context.xml:

<beans:property name="presidentName" value="Barack Obama" />
Run Code Online (Sandbox Code Playgroud)

有没有办法设置变量一次application-context.xml来表示字符串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">



    <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>
Run Code Online (Sandbox Code Playgroud)

小智 13

正如哈欠指出的那样,你可以定义一个新的字符串分类的春豆.

<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>
Run Code Online (Sandbox Code Playgroud)


Ara*_*ram 2

在 spring 中定义一个 bean,将其指定为抽象 (abstract="true") 并在那里注入 PresidentName 属性。然后,您可以通过将之前定义的抽象 bean 指定为父代来定义 3 个具体 bean。例如

<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
Run Code Online (Sandbox Code Playgroud)