我有一些使用JAXB API类的代码,这些类已作为Java 6/7/8中的JDK的一部分提供。当我用Java 9运行相同的代码时,在运行时得到错误,指示找不到JAXB类。

从Java 6开始,JAXB类就作为JDK的一部分提供了,那么为什么Java 9再也找不到这些类了呢?


当前回答

这招对我很管用:

<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");

到目前为止,作为一种变通方法,效果很好。不过,这看起来并不是一个完美的解决方案……

其他回答

转到您的构建。gradle和添加以下Java 9或Java 10的依赖项。

sourceCompatibility = 10 // You can also decrease your souce compatibility to 1.8 

//java 9+ does not have Jax B Dependents

    compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
    compile group: 'com.sun.xml.bind', name: 'jaxb-core', version: '2.3.0'
    compile group: 'com.sun.xml.bind', name: 'jaxb-impl', version: '2.3.0'
    compile group: 'javax.activation', name: 'activation', version: '1.1.1'

旧答案“问题通过切换到amazoncorretto解决” 新闻回答:我使用了最新的corretto,但类似jdk 1.8。无论如何,我们需要手动添加依赖项

在我的例子中(spring boot fat jar),我只是将以下内容添加到pom.xml。

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>

这是因为如果您使用的是JDK 9或更高版本,只需将此添加到您的pom

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>

我在App中遇到了同样的问题,在模块级别构建。gradle添加了视图绑定和数据绑定。

早些时候

viewBinding {
    enabled = true
}

dataBinding {
    enabled = true
}

解决

dataBinding {
    enabled = true
}

在项目级构建中。Gradle使用如下

classpath 'com.android.tools.build:gradle:3.6.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"