动态加载spring xml配置

在一个春天的应用程序的启动时,我想扫描计算机上的路径,找到jar文件,并从他们的XML配置文件构建一个春天的应用程序上下文。 将jar文件添加到类路径并创建一个ApplicationContext都是可以的。 但是我从新的上下文中找不到任何bean。 所有需要的依赖关系都可以在计算机上的特定路径(通过maven复制插件)的jar文件中获得,这些依赖项在基本的spring项目(例如spring依赖项本身)中是需要的。 代码是(在Kotlin语言中):

var loader = URLClassLoader(arrayOf(entry.toFile().toURL()), Thread.currentThread().contextClassLoader) ... val context = ClassPathXmlApplicationContext("classpath*:/$name")//name is xml file. I'm sure the address in classpath is right. context is not creating when the address in wrong. for example: classpath://$name val services = context.getBeanNamesForType(IService::class.java)//services is empty 

我已经尝试了许多其他的方式来加载XML,但没有一个是成功的。 例如:

 val beans = DefaultListableBeanFactory(applicationContext) val reader = XmlBeanDefinitionReader(beans) reader.beanClassLoader = loader reader.resourceLoader = resourceLoader reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD) jarFile.getInputStream(jarEntry).use { reader.loadBeanDefinitions(EncodedResource(InputStreamResource(it))) } beans.preInstantiateSingletons() 

jar文件里面的xml看起来像这样:

 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <import resource="classpath*:/xxx-logic-context.xml"/> <context:annotation-config/> <context:component-scan base-package="aa.bbb.ccc.server"/> </beans> 

这真的很有趣:当我使用包扫描功能定义常规Beans时,我可以用一种代码来获取bean

@talex的伟大答案引导了我。 我通过设置当前的类加载器来修复它:

 val loader = URLClassLoader(arrayOf(entry.toFile().toURL()), Thread.currentThread().contextClassLoader) Thread.currentThread().contextClassLoader = loader 
Interesting Posts