akirekadu
akirekadu

Reputation: 2357

Is there a shorthand for creating a String constant in Spring context XML file?

I need to define a string value in Spring context XML file that is shared by multiple beans.

This is how I do it:

<bean id="aSharedProperty" class="java.lang.String">
    <constructor-arg type="java.lang.String" value="All beans need me :)"/>
</bean>

Creating a java.lang.String bean by passing a constructor argument of java.lang.String seems kludgy.

Is there a shortcut?

I know this property can be passed using PropertyOverrideConfigurer, but I want to keep this property within the XML file.

Upvotes: 37

Views: 27777

Answers (4)

bm1729
bm1729

Reputation: 2375

Something I've used in the past is SpEL to make sure that a bean has the same value as another:

<bean id="myBean" class="xxx.yyy.Foo" >
    <property name="myProperty" value="1729" />
</bean>

<bean id="copyCat" class="xxx.yyy.Bar" >
    <property name="anotherProperty" value="#{myBean.myProperty}" />
</bean>

I have found this to be particularly useful when setting the value did something other than a simple assignment.

Upvotes: 4

beny23
beny23

Reputation: 35048

You may be able to use the following:

<bean id="abstractParent" abstract="true">
    <property name="sharedProperty" value="All child beans need me" />
</bean>

<bean id="bean1" class="MyClass1" parent="abstractParent">
    ...non-shared properties...
</bean>

<bean id="bean2" class="MyClass2" parent="abstractParent">
    ...non-shared properties...
</bean>

However, that relies on the property having the same name, so may not be applicable for you.

Upvotes: 4

Kaitsu
Kaitsu

Reputation: 4114

A shorthand to the solution proposed by mrembisz goes like this:

<context:property-placeholder properties-ref="myProperties"/>

<util:properties id="myProperties">
    <prop key="aSharedProperty">All beans need me :)</prop>
</util:properties>

Upvotes: 13

mrembisz
mrembisz

Reputation: 12880

You can use PropertyPlaceholderConfigurer and keep values in xml:

<context:property-placeholder properties-ref="myProperties"/>

<bean id="myProperties" 
    class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="properties">
    <props>
      <prop key="aSharedProperty">All beans need me :)</prop>
    </props>
  </property>
</bean>

Then you reference it with:

<bean id="myBean" class="my.package.MyClass">
  <property name="someField" value="${aSharedProperty}"/>
</bean>

Upvotes: 26

Related Questions