nas*_*000 34 java configuration spring
在我的Spring xml配置中,我试图让这样的东西起作用:
<beans>
<import resource="${file.to.import}" />
<!-- Other bean definitions -->
</beans>
Run Code Online (Sandbox Code Playgroud)
我想根据属性文件中的属性决定导入哪个文件.我知道我可以使用System属性,但我无法在启动时向JVM添加属性.
注:PropertyPlaceHolderConfigurer将无法正常工作.在运行任何BeanFactoryPostProcessor之前解析导入.import元素只能解析System.properties.
有人有一个简单的解决方案吗?我不想开始子类化框架类等等......
谢谢
Lou*_*cio 15
不幸的是,这比应该的要困难得多.在我的应用程序中,我完成了以下操作:
一个小的"引导程序"上下文,负责加载PropertyPlaceholderConfigurer bean和另一个负责引导应用程序上下文的bean.
上面提到的第二个bean将要加载的"真实"spring上下文文件作为输入.我将弹簧上下文文件组织起来,以便可配置部分在同一个地方是众所周知的.例如,我可能有3个配置文件:one.onpremise.xml,one.hosted.xml,one.multitenant.xml.bean以编程方式将这些上下文文件加载到当前应用程序上下文中.
这是有效的,因为上下文文件被指定为负责加载它们的bean的输入.如果你只是尝试进行导入,它将无法工作,正如你所提到的那样,但这会产生相同的效果,稍微多一些工作.bootstrap类看起来像这样:
public class Bootstrapper implements ApplicationContextAware, InitializingBean {
private WebApplicationContext context;
private String[] configLocations;
private String[] testConfigLocations;
private boolean loadTestConfigurations;
public void setConfigLocations(final String[] configLocations) {
this.configLocations = configLocations;
}
public void setTestConfigLocations(final String[] testConfigLocations) {
this.testConfigLocations = testConfigLocations;
}
public void setLoadTestConfigurations(final boolean loadTestConfigurations) {
this.loadTestConfigurations = loadTestConfigurations;
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
context = (WebApplicationContext) applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
String[] configsToLoad = configLocations;
if (loadTestConfigurations) {
configsToLoad = new String[configLocations.length + testConfigLocations.length];
arraycopy(configLocations, 0, configsToLoad, 0, configLocations.length);
arraycopy(testConfigLocations, 0, configsToLoad, configLocations.length, testConfigLocations.length);
}
context.setConfigLocations(configsToLoad);
context.refresh();
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,获取应用程序上下文,设置其配置位置,并告诉它自己刷新.这在我的应用程序中完美运行.
希望这可以帮助.
小智 5
Spring JIRA上存在一个旧问题,用于添加属性占位符支持导入(SPR-1358),该解决方案被解析为"无法修复",但此后一直提出使用EagerPropertyPlaceholderConfigurer的解决方案.
我一直在游说让SPR-1358重新开放,但到目前为止还没有回应.也许如果其他人将他们的用例添加到问题评论中,这将有助于提高认识.
为什么不:
所以你实际上颠倒了当前提出的解决方案。
归档时间: |
|
查看次数: |
44302 次 |
最近记录: |