rascio
rascio

Reputation: 9279

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?

Upvotes: 21

Views: 65864

Answers (3)

yankee
yankee

Reputation: 40840

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.

Upvotes: 10

rakesh yada
rakesh yada

Reputation: 27

This is also one of the way.

<bean id="str" class="com.example.Ex">
<constructor-arg type="java.lang.String" value="INDIA"/>

Upvotes: -6

Mr.Eddart
Mr.Eddart

Reputation: 10273

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>

Upvotes: 64

Related Questions