如何在Spring XML上下文中实现条件资源导入? [英] How to achieve conditional resource import in a Spring XML context?
问题描述
我想要实现的是动态(即基于配置文件中定义的属性)启用/禁用导入子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"/>
属性被解析(到布尔值),当为真时,导入上下文,否则它不是't。
Where the property is resolved (to a boolean) and when true the context is imported, otherwise it isn't.
到目前为止我的一些研究:
Some of my research so far:
-
编写自定义NamespaceHandler(及相关类),以便我可以在自己的命名空间中注册自己的自定义元素。例如:
< myns:import condition =some.property.nameresource =some-context.xml/>
这种方法的问题在于我不想从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.
推荐答案
现在这完全是可能,使用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;
}
}
}
最后,你把您想要包含在/com/example/context-fragment.xml中的bean定义
And then finally, you put the bean definitions you want included in the /com/example/context-fragment.xml
这篇关于如何在Spring XML上下文中实现条件资源导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!