define a string in spring context
I have 开发者_开发技巧three (A,B,C) spring context.xml, A is for the basic configuration, B and C import the A.
In a bean on A I have:
<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?
You could try an alternative way by declaring bean of type String, instead of dealing with 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
<bean id="str" class="java.lang.String">
<constructor-arg value="string_1"/>
</bean>
C
<bean id="str" class="java.lang.String">
<constructor-arg value="string_2"/>
</bean>
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:
<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.
This is also one of the way.
<bean id="str" class="com.example.Ex">
<constructor-arg type="java.lang.String" value="INDIA"/>
精彩评论