Is there a shorthand for creating a String constan

2020-05-19 04:27发布

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.

标签: java spring
4条回答
成全新的幸福
2楼-- · 2020-05-19 04:45

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>
查看更多
SAY GOODBYE
3楼-- · 2020-05-19 04:45

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.

查看更多
霸刀☆藐视天下
4楼-- · 2020-05-19 04:46

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.

查看更多
再贱就再见
5楼-- · 2020-05-19 05:07

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>
查看更多
登录 后发表回答