Conditions in Spring expression language(SpEL) used in bean definition
Asked Answered
L

3

5

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.

Louvar answered 22/11, 2010 at 14:45 Comment(0)
M
5

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.

Miscarry answered 1/12, 2010 at 23:12 Comment(0)
F
4

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.

Flyspeck answered 22/11, 2010 at 17:29 Comment(2)
I was really jazzed to see this, but <bean ... ref="#{ systemProperties['command.line.property'].equals('development') ? localLDAP : remoteLDAP }"/> doesn't work at all with "-Dcommand.line.property=development" defined on the java command line.Symbology
Unfortunately you can't use SpEL in a class attribute.Hyrup
M
0

it is not a question of using spel, but more of XML,afaik you can't do this in XML (but xslt)

the proper spring way for this scenario might be http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-class in combination with a "parent" interface for BeanA and BeanB

you could pass the parameter (system ? runtime specific ?) to the factory, which would create either BeanA or BeanB

Mussulman answered 22/11, 2010 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.