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

前端 未结 8 686
醉梦人生
醉梦人生 2020-11-27 14:25

What I would like to achieve is the ability to "dynamically" (i.e. based on a property defined in a configuration file) enable/disable the importing of a child Spr

相关标签:
8条回答
  • 2020-11-27 15:07

    For the record, Robert Maldon explains how to accomplish conditional definition of beans in this post: http://robertmaldon.blogspot.com/2007/04/conditionally-defining-spring-beans.html. It is a bit long to copy it here (besides, I don't think I should copy-paste his article anyway).

    The end result with this approach, adapted for your example, is:

    <condbean:cond test="${some.property.name}">
      <import resource="some-context.xml"/>
    </condbean:cond>
    

    It is certainly not so simple as Stephen C's solution, but it is much more poweful.

    0 讨论(0)
  • 2020-11-27 15:11

    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.
    0 讨论(0)
提交回复
热议问题