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

后端 未结 4 896
[愿得一人]
[愿得一人] 2021-02-01 14:36

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

This is how I do it:

<         


        
相关标签:
4条回答
  • 2021-02-01 14:57

    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>
    
    0 讨论(0)
  • 2021-02-01 14:58

    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>
    
    0 讨论(0)
  • 2021-02-01 15:07

    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.

    0 讨论(0)
  • 2021-02-01 15:23

    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.

    0 讨论(0)
提交回复
热议问题