动态加载spring xml config

时间:2016-09-19 14:40:45

标签: java xml spring classloader kotlin

在spring应用程序的启动时,我想扫描计算机上的路径,找到jar文件并从其中的xml配置文件构建spring应用程序上下文。将jar文件添加到类路径并创建ApplicationContext即可。但我无法从新的背景中找到任何豆子。所有需要的依赖项都可以在计算机上特定路径的jar文件中获得(通过maven复制器插件),期望基础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>

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

1 个答案:

答案 0 :(得分:1)

来自@talex的精彩回答引导我。我通过设置当前的类加载器来修复它:

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