我有一些使用JAXB API类的代码,这些类已作为Java 6/7/8中的JDK的一部分提供。当我用Java 9运行相同的代码时,在运行时得到错误,指示找不到JAXB类。
从Java 6开始,JAXB类就作为JDK的一部分提供了,那么为什么Java 9再也找不到这些类了呢?
我有一些使用JAXB API类的代码,这些类已作为Java 6/7/8中的JDK的一部分提供。当我用Java 9运行相同的代码时,在运行时得到错误,指示找不到JAXB类。
从Java 6开始,JAXB类就作为JDK的一部分提供了,那么为什么Java 9再也找不到这些类了呢?
当前回答
如果你使用的是上面提到的JDK 8,请遵循以下步骤:
添加javax.xml.bind依赖项
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
清洁maven 安装maven
其他回答
我跟踪了这个URL,下面的设置真的帮助了我。我在Macbook Pro中使用带有STS IDE的Java 10。这招很管用。
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
<version>1.2.0</version>
</dependency>
这对我很管用。只添加jaxb-api是不够的。
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${jaxb-api.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>${jaxb-api.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>${jaxb-api.version}</version>
</dependency>
这个问题的根本原因是使用JDK11的Gradle守护进程,要么你把你的JAVA_HOME设置为JDK11,要么你在使用JDK11运行的共享守护进程中运行Gradle任务。
为Android:
检查您的项目结构设置,您可以从那里将JDK更改为JDK8。 您还可以设置JAVA_HOME和指向java8的home。
由于JavaEE现在由https://jakarta.ee/管理,因此2.3.2的新Maven坐标为:
https://eclipse-ee4j.github.io/jaxb-ri/#maven-artifacts
第一个发布的jaxb。版本为2.3.2。
<properties>
<jaxb.version>2.3.2</jaxb.version>
</properties>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>${jaxb.version}</version>
</dependency>
这招对我很管用:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.7.0</version>
</dependency>
更新
正如@Jasper所建议的,为了避免依赖于整个EclipseLink库,你也可以只依赖于EclipseLink MOXy:
Maven
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.moxy</artifactId>
<version>2.7.3</version>
</dependency>
Gradle
compile group: 'org.eclipse.persistence', name: 'org.eclipse.persistence.moxy', version: '2.7.3'
作为我的Java 8应用程序的依赖项,该应用程序生成一个*.jar,它可以在JRE 8或JRE 9上运行,没有额外的参数。
此外,在使用JAXB API之前,需要在某处执行此命令:
System.setProperty("javax.xml.bind.JAXBContextFactory", "org.eclipse.persistence.jaxb.JAXBContextFactory");
到目前为止,作为一种变通方法,效果很好。不过,这看起来并不是一个完美的解决方案……