c12
c12

Reputation: 9827

Include/Exclude Spring Bean Property List Value Node

I would like to conditionally/dynamically display the <value>classpath:/resources/three.sql</value> value node in my spring xml configuration based on a system property, i.e. ${env}. Something like if ${env} is dev then include it else exclude it or if thats not easy then just conditionally pass in the all the value nodes from a system property. Is this possible?

<bean id="myBean"
          class="com.testMyBean">
        <property name="scripts">
            <list>
                <value>classpath:/resources/one.sql</value>
                <value>classpath:/resources/two.sql</value>
                <value>classpath:/resources/three.sql</value>
            </list>
        </property>
</bean>

Upvotes: 1

Views: 1965

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

You can use Spring profiles to conditionally include the beans.

Add a beans wrapper element with a profile specified:

<beans profile="dev">
    <bean id="myBean" class="com.testMyBean">
        <property name="scripts">
            <list>
                <value>classpath:/resources/one.sql</value>
                <value>classpath:/resources/two.sql</value>
                <value>classpath:/resources/three.sql</value>
            </list>
        </property>
    </bean>
</beans>

Then set this system property (VM argument) in your runtime configuration:

-Dspring.profiles.active="dev"

To specify the default profile for the application you can set a context parameter in your web.xml file:

<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>openshift</param-value>
</context-param>

Upvotes: 3

Sergey Morozov
Sergey Morozov

Reputation: 4608

Best way do it use profiles, as said above.

You can use multiple xml-files, where file name is parametrized ${env} variable.

root xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    <import resource="classpath:etc/abc-${env}.xml" />
   ...
<beans

abc-three.xml:(if ${env} == three)

<bean id="myBean" class="com.testMyBean">
    <property name="scripts">
        <list>
            <value>classpath:/resources/one.sql</value>
            <value>classpath:/resources/two.sql</value>
            <value>classpath:/resources/three.sql</value>
        </list>
    </property>
</bean>

abc-two.xml:(if ${env} == two)

<bean id="myBean" class="com.testMyBean">
    <property name="scripts">
        <list>
            <value>classpath:/resources/one.sql</value>
            <value>classpath:/resources/two.sql</value>
        </list>
    </property>
</bean>

Upvotes: 1

Related Questions