Conditions in Spring expression language(SpEL) used in bean definition

10,200

Solution 1

Environment profiles/Environment specific beans will be available in Spring 3.1 which should be released shortly - so you might want to wait for that.

There is no built in support for conditional beans in Spring 3.0. However, it could be achieved by using PropertyPlaceholderConfigurers and/or FactoryBeans.

Solution 2

There's no conditional mechanism for XML Spring bean defintion files. However, maybe this would work:

<bean class="#{prop=='a' ? BeanA : BeanB}"/>

But even if this approach worked, it wouldn't be the most readable one. My suggestion would be to use different set of XML configuration files and pick them depending on some global settings. Naturally you would put all the common beans (i.e. these whose definition is always the same) in a separate file and have it always included.

Share:
10,200
MTPy
Author by

MTPy

JEE,JSP,JSR-168 Portlets,Spring Batch,JPA

Updated on June 05, 2022

Comments

  • MTPy
    MTPy almost 2 years

    As far SpEL is used in Spring 3.0,

    I would like to ask, is it possible to do following(in bean definition .xml):

    <c:choose>
    
      <c:when test="#{prop=='a'}">
       <bean class="BeanA"/>
      </c:when>
    
      <c:otherwise>
       <bean class="BeanB"/>
      </c:otherwise>
    
    </c:choose>
    

    Someth. like in jstl.

    Thank you for help.