Maven 打包 WAR 部署到 JBoss 時報 Failed to create a new SAX parser。網上常見方案是刪除項目 lib 下的 xerces-2.6.2.jar、xml-apis.jar,但 Maven 會根據 pom.xml 依賴傳遞再次打入 WAR。本文記錄通過 Maven Dependency Exclusion 從源頭切斷傳遞依賴,徹底解決的過程。
Failed to create a new SAX parser
org.apache.xerces.parsers.XML11Configuration.parse(XML11Configuration.java:...)
...
Caused by: java.lang.ClassCastException: org.apache.xerces.parsers.XML11Configuration cannot be cast to org.xml.sax.XMLReader
本質:WAR 內攜帶的 xercesImpl、xml-apis 與 JBoss 服務端自帶的 XML 解析器版本衝突,導致類加載器加載到錯誤實現類。
dwr,DWR 默認傳遞依賴 xerces:xercesImpl 和 xml-apis:xml-apis。WEB-INF/lib。ClassCastException。pom.xml,切換到 Dependency Hierarchy 選項卡。xercesImpl 和 xml-apis 定位到具體節點。<dependency>
<groupId>org.directwebremoting</groupId>
<artifactId>dwr</artifactId>
<version>2.0.x</version>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
<exclusion>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
</exclusion>
</exclusions>
</dependency>
<exclusions> 告訴 Maven:「解析 dwr 依賴樹時,不要傳遞 這兩個 artifact」。打包後 WAR 的 WEB-INF/lib 不再包含它們,運行時使用 JBoss 內置解析器,衝突消失。
mvn clean package 重新打包。WEB-INF/lib 無 xercesImpl*、xml-apis*。# 1. 查看完整依賴樹,定位傳遞路徑
mvn dependency:tree -Dverbose | grep -E "xerces|xml-apis"
# 2. 分析衝突
mvn dependency:tree -Dincludes=xerces:xercesImpl,xml-apis:xml-apis
| 衝突庫 | 典型症狀 | 解決思路 |
|---|---|---|
| slf4j / log4j / logback 多版本 | ClassCastException、日志不輸出、多重綁定警告 | 排除傳遞,統一版本,或用 jboss-deployment-structure.xml 控制模塊隔離 |
| Jackson / Gson 不同版本 | 序列化異常、字段丟失 | 依賴管理統一版本,排除舊傳遞 |
| Spring 核心包版本不一致 | NoSuchMethodError、BeanCreationException | BOM 統一版本 (spring-framework-bom) |
Failed to create a new SAX parser 核心是 WAR 內攜帶舊版 XML 解析器 JAR 與容器衝突。利用 Maven <exclusions> 從依賴樹源頭切斷傳遞,比手動刪 JAR 徹底、可維護。養成 mvn dependency:tree 定位傳遞路徑、<dependencyManagement> 統一版本的習慣,是避免 Jar 地獄的關鍵。