How to achieve conditional resource import in a Spring XML context?

Prior to Spring 4, the closest you can get using standard Spring components is:

<import resource="Whatever-${yyzzy}.xml"/>

where ${xyzzy} interpolates a property from the system properties. (I use a hacky custom version of the context loader class that adds properties from other places to the system properties object before starting the loading process.)

But you can also get away with importing lots of unnecessary stuff … and use various tricks to only cause the necessary beans to be instantiated. These tricks include:

  • placeholder and property substitution
  • selecting different beans using the new Spring expression language,
  • bean aliases with placeholders in the target name,
  • lazy bean initialization, and
  • smart bean factories.

Leave a Comment