如何在 Spring XML 上下文中实现条件资源导入? [英] How to achieve conditional resource import in a Spring XML context?

查看:33
本文介绍了如何在 Spring XML 上下文中实现条件资源导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现的是动态"(即基于配置文件中定义的属性)启用/禁用子 Spring XML 上下文的导入.

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 Spring XML context.

我想像这样:

<import condition="some.property.name" resource="some-context.xml"/>

属性解析(为布尔值)的位置,当为 true 时导入上下文,否则不导入.

Where the property is resolved (to a boolean) and when true the context is imported, otherwise it isn't.

我目前的一些研究:

  • 编写自定义 NamespaceHandler(和相关类),以便我可以在自己的命名空间中注册自己的自定义元素.例如:

这种方法的问题在于,我不想从 Spring 复制整个资源导入逻辑,而且我不清楚需要委托什么来执行此操作.

The problem with this approach is that I do not want to replicate the entire resource importing logic from Spring and it isn't obvious to me what I need to delegate to to do this.

覆盖 DefaultBeanDefinitionDocumentReader 以扩展导入"的行为元素解析和解释(发生在 importBeanDefinitionResource 方法中).但是我不确定在哪里可以注册这个扩展.

Overriding DefaultBeanDefinitionDocumentReader to extend the behaviour of the "import" element parsing and interpretation (which happens there in the importBeanDefinitionResource method). However I'm not sure where I can register this extension.

推荐答案

现在完全可以使用 Spring 4.

This is now completely possible, using Spring 4.

在您的主应用程序内容文件中

In your main application content file

<bean class="com.example.MyConditionalConfiguration"/>

MyConditionalConfiguration 看起来像

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;
         }
    }
}

最后,您将想要包含的 bean 定义放入/com/example/context-fragment.xml

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

请参阅 @Conditional 的 JavaDoc

这篇关于如何在 Spring XML 上下文中实现条件资源导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆