在 spring 上下文中定义一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6652610/
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
define a string in spring context
提问by rascio
I have three (A,B,C) spring context.xml, A is for the basic configuration, B and C import the A.
我有三个(A,B,C)spring context.xml,A是基本配置,B和C导入A。
In a bean on A I have:
在 AI 上的 bean 中有:
<bean class="com.example.Ex">
<property name="aString" value="${myString}" />
</bean>
now I want to define the property myString on B and C context, is possible to do it without create and loads two different properties file?
现在我想在 B 和 C 上下文中定义属性 myString,是否可以在不创建和加载两个不同的属性文件的情况下做到这一点?
回答by Mr.Eddart
You could try an alternative way by declaring bean of type String, instead of dealing with Properties.
您可以通过声明 String 类型的 bean 来尝试另一种方法,而不是处理 Properties。
This way:
这边走:
A
一种
<bean class="com.example.Ex">
<property name="aString" ref="str" />
</bean>
And then you declare in your B and C contexts the "str" reference this way:
然后在 B 和 C 上下文中以这种方式声明“str”引用:
B
乙
<bean id="str" class="java.lang.String">
<constructor-arg value="string_1"/>
</bean>
C
C
<bean id="str" class="java.lang.String">
<constructor-arg value="string_2"/>
</bean>
回答by yankee
For completeness here another way of creating a string:
为了完整起见,另一种创建字符串的方法:
Instead of calling the String constructor which forces a new object to be created unnecessarily it may be a better idea to use the valueOf method which can here serve as a "do nothing" constructor:
与其调用强制创建不必要的新对象的 String 构造函数,不如使用 valueOf 方法,该方法在这里可以用作“什么都不做”的构造函数:
<bean id="str" class="java.lang.String" factory-method="valueOf">
<constructor-arg value="string_1"/>
</bean>
However this is only academic as the overhead of parsing the additional XML attribute which will cause strings to be created as well may be greater than the performance gain of calling valueOf instead of the constructor.
然而,这只是学术性的,因为解析额外的 XML 属性的开销也会导致创建字符串,这可能大于调用 valueOf 而不是构造函数的性能增益。
回答by rakesh yada
This is also one of the way.
这也是方法之一。
<bean id="str" class="com.example.Ex">
<constructor-arg type="java.lang.String" value="INDIA"/>

