java 如何在 application-context.xml 中设置局部变量来表示重复值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4059116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set a local variable in application-context.xml to represent a repeating value?
提问by kors
If the president changes, I would have to change the value of presidentName
three times below in the application-context.xml
:
如果总裁换了,我就得把presidentName
下面的值改三遍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
.
有没有办法设置变量一次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>
回答by amphied
As yawn pointed out you can define a new String-classed spring bean.
正如 yawn 指出的,您可以定义一个新的 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>
回答by Aravind Yarram
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.
在 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
回答by yawn
Define president
as String-classed bean?
定义president
为字符串类 bean?