Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 744
tonicsoft Avatar asked Oct 06 '16 13:10

tonicsoft


People also ask

Where is Spring XML configuration file?

You will need to add spring. xml file at the location - src/main/resources folder. You can have your directory structure inside this directory as - src/main/resources/com/vipin/dao. src/main/java directory is preferred for java classes.


1 Answers

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.

like image 128
eltabo Avatar answered Sep 22 '22 15:09

eltabo