获取应用程序上下文

时间:2009-11-07 03:20:08

标签: spring

有没有办法从文件系统中的上下文和类路径一次获取ApplicationContext?而不是使用FileSystemXmlApplicationContext然后使用ClassPathXmlApplicationContext并将fileSystemApplicationContext作为父级传递?

1 个答案:

答案 0 :(得分:3)

我建议您查看org.springframework.context.support.GenericApplicationContext。与org.springframework.beans.factory.xml.XmlBeanDefinitionReader一起,它可以为您提供所需的灵活性。 GenericApplicationContext's javadoc

上有一个代码示例

您的代码如下:

GenericApplicationContext ctx = new GenericApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
xmlReader.loadBeanDefinitions(new ClassPathResource("classpathContext.xml"));
xmlReader.loadBeanDefinitions(new FileSystemResource("fileSystemContext.xml"));

请注意,XmlBeanDefinitionReader还有一个方法loadBeanDefinitions(String),然后使用org.springframework.core.io.ResourceLoader来处理相应的资源。在这种情况下,您的代码将如下所示:

GenericApplicationContext ctx = new GenericApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
xmlReader.loadBeanDefinitions("classpath:classpathContext.xml"));
xmlReader.loadBeanDefinitions("file:fileSystemContext.xml"));
相关问题