简体   繁体   中英

How can I set Spring property from the XML configuration file?

I have some spring config that uses a property, like so:

<bean id="foo" class="...">
    <constructor-arg value="${aProperty}"/>
</bean>

Obviously I know I can resolve this property by having a properties file (say example.properties):

aProperty=value

and importing this file in the Spring config:

<bean id="propertyConfiguration" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>example.properties</value>
        </list>
    </property>
</bean>

My question is, can I set this property directly in the XML file instead of having to create a separate properties file? Something like this would be ideal:

<set-property name="aProperty" value="value"/>

Maven has a similar feature for pom files:

<properties><aProperty>value</aProperty></properies>

The goal of using a properties file is uncouple values from Spring configuration files, so it's a little weird define a property in the same configuration file. Nevertheless you always can add properties to your PropertyPlaceholderConfigurer:

<bean id="propertyConfiguration" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>example.properties</value>
        </list>
    </property>
    <property name="properties">
        <props>
            <prop key="aa">bb</prop>
            <prop key="cc">dd</prop>
        </props>
    </property>
</bean>

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM