如何升级JDK中使用的JAXB RI版本?(Maven构建场景)
如何在JDK 7中升级JAXB RI版本(Maven构建)
当然可以通过Maven来覆盖JDK自带的JAXB RI版本,解决你遇到的binding.xjb文件读取问题!JDK 7自带的2.2.4-1确实有不少已知缺陷,升级到2.2.8或更新的修复版本就能搞定。下面是具体的配置步骤和注意事项:
1. 先排除JDK自带的JAXB依赖
JDK 7会自带JAXB RI,我们得先让Maven忽略这些内置依赖,避免版本冲突。最稳妥的方式是在依赖和插件中明确指定我们要使用的版本,或者直接在插件配置中引入新依赖覆盖默认。
2. 引入指定版本的JAXB RI依赖
直接在你的pom.xml中添加JAXB的API和实现依赖,推荐用2.2.11版本(比2.2.8修复了更多问题,且兼容JDK 7):
<dependencies> <!-- JAXB API 核心包 --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.2.11</version> </dependency> <!-- JAXB RI 实现包(运行时需要) --> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.2.11</version> <scope>runtime</scope> </dependency> <!-- JAXB XJC 编译工具(编译XSD时需要) --> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-xjc</artifactId> <version>2.2.11</version> <scope>provided</scope> </dependency> </dependencies>
3. 配置JAXB Maven插件(如果用XJC编译XSD)
如果你是用jaxb2-maven-plugin来编译XSD文件,一定要在插件里指定我们引入的JAXB版本,不然插件还是会用JDK自带的工具:
<build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</artifactId> <version>2.5.0</version> <executions> <execution> <goals> <goal>xjc</goal> </goals> </execution> </executions> <!-- 让插件使用我们指定的JAXB版本 --> <dependencies> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-xjc</artifactId> <version>2.2.11</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.2.11</version> </dependency> </dependencies> <configuration> <!-- 这里替换成你的XSD和binding.xjb路径 --> <schemaDirectory>${project.basedir}/src/main/resources/xsd</schemaDirectory> <bindingDirectory>${project.basedir}/src/main/resources</bindingDirectory> <bindingFiles>binding.xjb</bindingFiles> </configuration> </plugin> </plugins> </build>
4. 解决运行时类加载优先级问题
有时候JDK自带的JAXB类会被优先加载,导致升级后的版本不生效。这时候可以在运行程序时添加JVM参数,强制使用我们引入的JAXB实现:
-Djavax.xml.bind.context.factory=com.sun.xml.bind.v2.ContextFactory
这个参数会告诉JVM使用我们引入的JAXB RI上下文工厂,而不是JDK内置的。
验证升级是否成功
可以写一段简单的代码确认当前使用的JAXB版本:
import javax.xml.bind.JAXBContext; import com.sun.xml.bind.v2.runtime.JAXBContextImpl; public class JaxbVersionChecker { public static void main(String[] args) throws Exception { JAXBContext context = JAXBContext.newInstance(Object.class); if (context instanceof JAXBContextImpl) { JAXBContextImpl impl = (JAXBContextImpl) context; System.out.println("当前JAXB RI版本:" + impl.getVersion()); } } }
运行后如果输出是你指定的版本(比如2.2.11),就说明升级成功啦!
内容的提问来源于stack exchange,提问作者jeff porter




