java - 动态加载spring xml配置

标签 java xml spring classloader kotlin

在 Spring 应用程序启动时,我想扫描计算机上的路径,找到 jar 文件并从其中的 xml 配置文件构建 Spring 应用程序上下文。将 jar 文件添加到类路径并创建 ApplicationContext 一切都可以。但我无法从新的上下文中找到任何 bean 。所有需要的依赖项都可以在计算机上特定路径的 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

最佳答案

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

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

关于java - 动态加载spring xml配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39575901/

相关文章:

java - 将 Vaadin Designer 连接到 Java 代码

java - 在 Java 8 中重置时间戳

java - 当我用Java中的Scanner类读取.txt文件时,如何只能读取字符串或整数

javascript - 从 XML 获取 bool 变量(不是字符串)

spring - 从gs-production-web-service开始

java - 使用Spring和Hibernate跨多个数据库进行分布式事务的 'best'方法是什么

java - 使用 Spring Web 服务时的 Enum 类型转换

java - Eclipse XML 编辑器显示 android1 不是 android 并且没有自动完成

android - 使用 Android 库项目时,如何正确引用 xml 资源?

java - 设置构造函数参数时无法解析对 bean 'entityManagerFactory' 的引用