WildFly中Spring模块访问WAR/lib类的问题求助
你的问题核心在于WildFly的模块类加载器与部署类加载器是隔离的:Spring模块(org.springframework.spring)的类加载器默认无法访问EAR/WAR部署中的依赖类,哪怕你把commons-pool2放到ear/lib或者设置子部署隔离为false,这些配置只影响部署内部的类共享,不涉及模块到部署的类访问。
下面给你几个可行的解决方案,按推荐优先级排序:
方案1:将commons-pool2纳入Spring模块的依赖(最直接)
既然CommonsPool2TargetSource是Spring模块里的类,它需要的commons-pool2依赖直接放到Spring模块里是最合理的:
- 找到WildFly中Spring模块的目录(通常是
modules/org/springframework/spring/main) - 将
commons-pool2-2.4.2.jar复制到这个目录下 - 修改该目录下的
module.xml,在<resources>节点中添加:<resource-root path="commons-pool2-2.4.2.jar"/> - 同时检查
commons-pool2是否有其他依赖(比如commons-logging),如果有,确保Spring模块的<dependencies>里已经包含对应的模块(你的Spring模块已经依赖了org.apache.commons.logging,所以这一步可能不用额外操作)
重启WildFly后,Spring模块就能直接找到commons-pool2的类了。
方案2:让Spring模块优先从部署加载类(无需修改模块)
如果你不想修改Spring模块的配置,可以在jboss-deployment-structure.xml中给Spring模块依赖添加local-last="true"属性,让模块的类加载器先从部署的类路径查找类:
<dependencies> <module export="true" meta-inf="export" name="org.springframework.spring" local-last="true"/> <!-- 其他原有依赖保持不变 --> </dependencies>
这个配置会改变类加载顺序:Spring模块在加载类时,会先从你的EAR/WAR的类路径(包括WEB-INF/lib或ear/lib)找,再从模块自身的jar找,这样就能找到部署中的commons-pool2了。
方案3:将commons-pool2部署为独立的WildFly模块
把commons-pool2做成一个独立的全局模块,让Spring模块和你的部署都依赖它:
- 在WildFly的
modules目录下创建org/apache/commons/pool2/main目录 - 复制
commons-pool2-2.4.2.jar到该目录,创建module.xml:<?xml version='1.0' encoding='UTF-8'?> <module xmlns="urn:jboss:module:1.5" name="org.apache.commons.pool2"> <resources> <resource-root path="commons-pool2-2.4.2.jar"/> </resources> <dependencies> <module name="org.apache.commons.logging"/> </dependencies> </module> - 修改Spring模块的
module.xml,在<dependencies>中添加:<module name="org.apache.commons.pool2"/> - (可选)如果你的部署代码也需要直接使用
commons-pool2,可以在jboss-deployment-structure.xml的<dependencies>中也添加这个模块依赖。
为什么之前的尝试无效?
你提到的将commons-pool2移到ear/lib并设置<ear-subdeployments-isolated>false</ear-subdeployments-isolated>,这个配置只是让EAR下的子部署(比如你的myApp.war)之间可以共享类,但Spring模块属于WildFly的全局模块体系,和部署的类加载器是完全独立的层级,所以这个设置无法让模块访问部署内的类。
内容的提问来源于stack exchange,提问作者Wizzard

