我正在尝试在OpenJ9(JDK14(上加载Hibernate XML配置,但由于JAXB不再是JDK的一部分,因此出现此错误:
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.ValidationEventHandler
我试图遵循以下一些答案:如何解决java.lang.NoClassDefFoundError:Java 9中的javax/xml/bind/JAXBException,但似乎没有人在OpenJ9上工作,当尝试包含任何依赖项时,我收到以下错误:
Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:278)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:421)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
... 5 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:788)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:1081)
at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:276)
... 9 more
我在拼图中发现了缺失的部分,需要在系统属性中设置javax.xml.bind.JAXBContextFactory
。
因此,解决方案是将 JAXB 添加到依赖项列表中:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.moxy</artifactId>
<version>2.7.3</version>
</dependency>
然后在代码中(或在 JVM 启动时(将系统属性设置为指向正确的工厂。
System.setProperty("javax.xml.bind.JAXBContextFactory", "org.eclipse.persistence.jaxb.JAXBContextFactory");
最后,由于我在自定义类加载器中运行,因此必须设置ContextClassLoader
,否则找不到工厂。
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());