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

前端 未结 8 733
醉梦人生
醉梦人生 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:05

    This is now completely possible, using Spring 4.

    In your main application content file

    
    

    And the MyConditionalConfiguration looks like

    @Configuration
    @Conditional(MyConditionalConfiguration.Condition.class)
    @ImportResource("/com/example/context-fragment.xml")
    public class MyConditionalConfiguration {
        static class Condition implements ConfigurationCondition {
             @Override
             public ConfigurationPhase getConfigurationPhase() {
                 return ConfigurationPhase.PARSE_CONFIGURATION;
             }
             @Override
             public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
                 // only load context-fragment.xml if the system property is defined
                 return System.getProperty("com.example.context-fragment") != null;
             }
        }
    }
    

    And then finally, you put the bean definitions you want included in the /com/example/context-fragment.xml

    See the JavaDoc for @Conditional

提交回复
热议问题