How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
Asked Answered
E

46

1250

I have some code that uses JAXB API classes which have been provided as a part of the JDK in Java 6/7/8. When I run the same code with Java 9, at runtime I get errors indicating that JAXB classes can not be found.

The JAXB classes have been provided as a part of the JDK since Java 6, so why can Java 9 no longer find these classes?

Epanodos answered 23/4, 2017 at 17:40 Comment(7)
The additional part in this answer relates to the migration of these API's.Condense
building with Java 8 will get your code to compile yes, but when you try to run that compiled code on Java 9+ it will fail because JAX-B is not present.Epanodos
For Java 11, this article's solution is up to date: crunchify.com/java-11-and-javax-xml-bind-jaxbcontextBoatwright
see wiki.bitplan.com/index.php/Java8Oxide
See the way I fixed it her :- AnswerDeoxidize
Does this answer your question? Replacements for deprecated JPMS modules with Java EE APIsPancake
Are you found the answer @AndyGuibertHubie
E
1794

The JAXB APIs are considered to be Java EE APIs and therefore are no longer contained on the default classpath in Java SE 9. In Java 11, they are completely removed from the JDK.

Java 9 introduces the concepts of modules, and by default, the java.se aggregate module is available on the classpath (or rather, module-path). As the name implies, the java.se aggregate module does not include the Java EE APIs that have been traditionally bundled with Java 6/7/8.

Fortunately, these Java EE APIs that were provided in JDK 6/7/8 are still in the JDK, but they just aren't on the classpath by default. The extra Java EE APIs are provided in the following modules:

java.activation
java.corba
java.transaction
java.xml.bind  << This one contains the JAXB APIs
java.xml.ws
java.xml.ws.annotation

Quick and dirty solution: (JDK 9/10 only)

To make the JAXB APIs available at runtime, specify the following command-line option:

--add-modules java.xml.bind

But I still need this to work with Java 8!!!

If you try specifying --add-modules with an older JDK, it will blow up because it's an unrecognized option. I suggest one of two options:

  1. You can set any Java 9+ only options using the JDK_JAVA_OPTIONS environment variable. This environment variable is automatically read by the java launcher for Java 9+.
  2. You can add the -XX:+IgnoreUnrecognizedVMOptions to make the JVM silently ignore unrecognized options, instead of blowing up. But beware! Any other command-line arguments you use will no longer be validated for you by the JVM. This option works with Oracle/OpenJDK as well as IBM JDK (as of JDK 8sr4).

Alternate quick solution: (JDK 9/10 only)

Note that you can make all of the above Java EE modules available at run time by specifying the --add-modules java.se.ee option. The java.se.ee module is an aggregate module that includes java.se.ee as well as the above Java EE API modules. Note, this doesn't work on Java 11 because java.se.ee was removed in Java 11.


Proper long-term solution: (JDK 9 and beyond)

The Java EE API modules listed above are all marked @Deprecated(forRemoval=true) because they are scheduled for removal in Java 11. So the --add-module approach will no longer work in Java 11 out-of-the-box.

What you will need to do in Java 11 and forward is include your own copy of the Java EE APIs on the classpath or module path. For example, you can add the JAX-B APIs as a Maven dependency like this:

<!-- API, java.xml.bind module -->
<dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>2.3.2</version>
</dependency>

<!-- Runtime, com.sun.xml.bind module -->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.2</version>
</dependency>

See the JAXB Reference Implementation page for more details on JAXB.

For full details on Java modularity, see JEP 261: Module System

As of July 2022, the latest version of the bind-api and jaxb-runtime is 4.0.0. So you can also use

    <version>4.0.0</version>

...within those dependency clauses. But if you do so, the package names have changed from javax.xml.bind... to jakarta.xml.bind.... You will need to modify your source code to use these later versions of the JARs.

For Gradle or Android Studio developer: (JDK 9 and beyond)

Add the following dependencies to your build.gradle file:

dependencies {
    // JAX-B dependencies for JDK 9+
    implementation "jakarta.xml.bind:jakarta.xml.bind-api:2.3.2"
    implementation "org.glassfish.jaxb:jaxb-runtime:2.3.2"
}
Epanodos answered 23/4, 2017 at 17:40 Comment(36)
So just add it to your gradle dependencies?Lowminded
So if the Java EE API modules are marked deprecated does that mean it is a possibility that in Java 10 JAXB will no longer be available at runtime in Java 10? That seems like a step backwards. We will have to go back to the pre-6 practice of including JAXB as a dependency.Derogatory
I'm not sure what release it will be removed in, but according to the Java 9 javadoc, the module is marked @Deprecated(forRemoval=true) so its safe to say it will be removed eventually. See here: download.java.net/java/jdk9/docs/api/java.xml.bind-summary.htmlEpanodos
It is my understanding that the intent is to evaluate how much depends on the module before fully deciding when/if to remove it (see here), but for now it is definitely intended to eventually be removed at some future point (and projects are expected to use an external dependency for the functionality). With the new release schedule for Java, I'm not real clear if there even will be something called "Java 10" or not, or exactly when this is able to be removed.Advowson
Is there any way to solve that issue by modifying PATH, or maybe CLASSPATH in Windows environments? I'm looking forward to start working with Android SDK, but it looks like with JRE8(9) the only option would be to modify the tools scripts manually... This is definitely not the first time when breaking change of one Java module introduces collapse of others... But - it still sucks same way it did first time :) . Thanks in advance.Raguelragweed
Using --add-modules java.se.ee or --add-modules ALL-SYSTEM as a workaround is not recommended according to migration guide here docs.oracle.com/javase/9/migrate under section Modules Shared with Java EE Not Resolved by Default --> point 1Kohlrabi
what if I am using sbt? can I modify build.sbt to add java.se.ee?Raimundo
Alone jaxb-api dependency is not enough (anymore?). Please, refer my version of the solution: https://mcmap.net/q/22042/-how-to-resolve-java-lang-noclassdeffounderror-javax-xml-bind-jaxbexceptionZoophilous
@Zoophilous it depends on how deeply the application is using JAX-B -- sometimes just the API is sufficient. I've updated my answer to indicate which version of API/impl people should use if they want to match Java 6/7/8Epanodos
Why not 2.3.0?Zoophilous
Looks like 2.3.0 didn't release until 2017 (after Java 8 was released). I was going off of this wikipedia page for the JavaSE to JAX-B version mappings: en.wikipedia.org/wiki/Java_Architecture_for_XML_BindingEpanodos
Adding the dependencies to my pom.xml resolved the problem!Austere
The version 2.2.8 does not exist for jaxb-core and jaxb-impl anymore. Use 2.2.11 or 2.3.0 works fine.Ry
Thanks for pointing that out @MincongHuang, I've updated the answer to show 2.2.11 instead of 2.2.8 (didn't go to 2.3.0 in order to best match JDK 8)Epanodos
With Java 10 officially released, we can confirm that the add-modules method will still work. The javax.xml.bind and other JavaEE classes are scheduled for removal in Java 11, per JEP-320.Luker
Never use java.se.ee module. Neither via requires, nor via --add-modules. This module is gone in Java 11 and your code will break. Instead, use specific module names (e.g. java.xml.bind).Facer
@Facer it doesn't matter if you specify java.se.ee vs. java.xml.bind, both modules will be removed in Java 11Epanodos
@AndyGuibert But java.xml.bind will continue to work as a Maven dependency. java.se.ee has no Maven equivalent.Facer
And now Java 11 is released and the java.se.ee module has been removed, so the --add-modules solution does not work anymore. Use the recommended solution instead: add JAXB as a separate dependency.Jadda
The JEP has links to maven central searches for each of the artifacts that's been removed.Quincuncial
When trying to remain compatible to the old java8 version of my program, should I use the latest versions or 2.2.8 (meaning 2.2.8-b01)? What about 2.2.11 versus 2.3.0/2.3.1?Upi
I would recommend the newest 2.2.X version. The only difference between 2.2.X and 2.3.X is support for JPMS modules (e.g. adding a module-info).Epanodos
activation is not needed, since it's already included by jaxb-api.Boatwright
I have java 11, how am i supposed to change the sdk manager to make it work. Bc i just wanted to make an android Game with Unity. That's all i wanted to do and now I've wasted 3 hours reading forums with suggestions that don't workAnaconda
--add-modules java.se.ee, for me only worked with java 10 and tomcat 9Intestate
DatatypeConfigurationException: Provider org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl not foundQuadragesima
i've added these dependencies and it is still giving me the same error. any ideas why?Spagyric
Is there a way to fix this as a user? Is it possible to download JAXB, add it to my CLASSPATH and then have the program in question just work by itself? (I've been trying this, but it isn't working, so I wanted to check whether it's actually possible or I'm just doing something wrong).Hyades
@AndyGuibert - I have an app as a war file. I cannot modify the code. So, how do I fix the exception? How do I download the jaxb dependencies and add them to classpath so that the war file can use them?Deduction
@Hyades check which packages you're missing. Odds are you will need a <2.0.0 version, which still uses javax package naming instead of jakarta.Voltammeter
If you use Linux and decided to use java 8, you must make sure to use the correct version of java. Review this marcotoscano.org/2021/08/…Octavus
I am so confused of why this works for 2.3.0, but does not for 3.1.0 :|Fairway
If you use 2.3.0, the package names are the same as before: javax.xml.bind.... If you use later versions, like 3.x and 4.x, then you need to modify your code to use packages like jakarta.xml.bind...Leathaleather
In my Android project, I add 2.3.2 to build.gradle and it throws a new error: Unable to load class 'javax.xml.bind.JAXBException'. Any ideas?Blesbok
in my case, open my old 2020 Android Studio projects. just download android studio Artic Fox Patch 3. and set grandle JDK to 1.8 on Project structure. im successfully build and running the project. hope it helped.Winepress
After adding dependencies also make sure to use them. I made the mistake of trying various dependencies and combinations while all I needed to do was to change the imports in code. For whatever reason the old javax imports were still valid, but once changed to jakarta, the exception was goneSirree
H
411

In my case (spring boot fat jar) I just add the following to pom.xml.

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
Hanukkah answered 21/11, 2017 at 12:7 Comment(9)
Just for reference github.com/spring-projects/spring-boot/wiki/…Inofficious
Can I add this with <scope>runtime</scope>?Centrosome
Adding gradle dependency like this testCompile('javax.xml.bind:jaxb-api') worked for me.Bongbongo
why do we need this? is it because Java 9 or 10 does not include this package?Aec
Like @Bongbongo mentioned, no need to specify the version of jaxb-api when using Spring Boot. Boot manages the version automatically.Ethanethane
I suggest to use <scope>runtime</scope> for such caseMercier
@Tuno's link didn't work for me, fixed link is: github.com/spring-projects/spring-boot/wiki/…Guibert
@all I'm using JDK 13. I declared my class with '@Service' annotation and when i try to fetch using '@Autowired' annotation it gives me error because of this dependency. So i'm confused if it is necessary for regular operation of '@Autowire' then why it getting deprecated or changed.Broadbill
Worked for me. JDK 8Cappello
P
121

Clean solution for all JDKs >= 9

You need to add two dependencies to your build

  • the jaxb-api
  • a jaxb implementation

As an implementation I chose to use the reference implementation by glassfish to get rid of old com.sun classes / libraries. So as a result I added in my maven build

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

<dependency>
  <groupId>org.glassfish.jaxb</groupId>
  <artifactId>jaxb-runtime</artifactId>
  <version>2.3.1</version>
</dependency>

Note that from version 2.3.1 you don't need to add the javax.activation any longer. (see https://github.com/eclipse-ee4j/jaxb-ri/issues/1222)

Pledget answered 18/10, 2018 at 10:37 Comment(5)
Is the javax.xml.bind module really required? My code in JDK 11 works without it.Sukiyaki
@Sukiyaki I am not sure. The jaxb-runtime jar and the api-jar do not share the same classes/packages. I guess it depends on your code. If your code does not use the classes from the package 'javax.xml.bind' then you probably don't need it. The topic of this thread is that 'javax/xml/bind/JAXBException' cannot be found; this class is only in the jaxb-api.Pledget
Works perfectly with multi-module project in java 12.Amazing
Works in JDK 11.Fredella
where is pom.xml file in project which is writable , in my project all pom.xml file only readbale, Is I need to create another one, if yes where i create this. @SebastianTheesHubie
Z
89

None of these solutions worked fine for me in the recent JDK 9.0.1.

I found that this list of dependencies is enough for a proper functioning, so you don't need to explicitly specify --add-module (though it is specified within these dependencies's pom's). The only you need is to specify this list of dependencies:

<dependencies>
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-runtime</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
</dependencies>
Zoophilous answered 7/1, 2018 at 12:6 Comment(12)
For JDK 8, remove the jaxb-core and jaxb-impl from above.Inside
Where do i find the corresponding file ?Bickerstaff
Which file @Anil?Zoophilous
@Zoophilous , the above mentioned xml file to add dependencyBickerstaff
@Bickerstaff this is a pom.xml file of the Maven configuration. If you don't know what is that, then it is better to start from begginingZoophilous
@Andremoniy, thanks for the suggestion. But i am not getting proper resources.Bickerstaff
An illegal reflective access operation has occurred WARNING: Illegal reflective access by com.sun.xml.bind.v2.runtime.reflect.opt.Injector (file:/C:/Users/eis/.m2/repository/com/sun/xml/bind/jaxb-impl/2.3.0/jaxb-impl-2.3.0.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int) WARNING: Please consider reporting this to the maintainers of com.sun.xml.bind.v2.runtime.reflect.opt.Injector WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future releaseHub
This worked for me on JDK 9.0.4 (I was calling JAXB related code through a Maven plugin with Maven 3.5.3). Although I would use <dependency> <groupId>javax.activation</groupId> <artifactId>javax.activation-api</artifactId> <version>1.2.0</version> </dependency> as last dependency.Wiltonwiltsey
Awesome. I had a situation where - for some reason - a spring boot app would run in intellij CE but not eclipse on mac, and in eclipse but not intellij CE on win10. Being able to work in one IDE on two platforms is an advantage.Never
https://mcmap.net/q/22047/-proper-fix-for-java-10-complaining-about-illegal-reflection-access-by-jaxb-impl-2-3-0 has a solution for the illegal reflective accessAfflux
and where do i put the XML of this.Anaconda
in my project pom.xml file only readable format , what does i need to do ? @ZoophilousHubie
M
51

This worked for me:

<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>

Update

As @Jasper suggested, in order to avoid depending on the entire EclipseLink library, you can also just depend on 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'

As dependencies for my Java 8 app, which produces a *.jar which can be run by both JRE 8 or JRE 9 with no additional arguments.

In addition, this needs to be executed somewhere before JAXB API will be used:

System.setProperty("javax.xml.bind.JAXBContextFactory", "org.eclipse.persistence.jaxb.JAXBContextFactory");

Works great so far, as a workaround. Doesn't look like a perfect solution though...

Melburn answered 27/9, 2017 at 18:40 Comment(9)
adding org.eclipse.persistence:eclipselink just to get JAXB APIs is a very heavy-weight dependency, unless you are already using eclipselink?Epanodos
Yes it is heavy (~9mb) and yes I've been using that already. I've mentioned that this is simply an alternative workaround for those who, maybe temporary, will have to use both 8 and 9 JREs for the same jar/war without providing command-line arguments.Melburn
for the sake of interop between JDK 8 & 9, I would recommend using the -XX:+IgnoreUnrecognizedVMOptions command line option (updated my answer with details)Epanodos
System.setProperty("javax.xml.bind.JAXBContextFactory", "org.eclipse.persistence.jaxb.JAXBContextFactory"); does not work for meArgybargy
Make sure to add javax.xml.bind dependency as wellMelburn
To avoid depending on the entire EclipseLink library, you can also just depend on EclipseLink MOXy: groupId org.eclipse.persistence, artifactId org.eclipse.persistence.moxy.Jadda
where to i put this xmlAnaconda
@IchHabsDrauf add it to your Maven project build (pom.xml) fileMelburn
I got this exception: "javax.xml.bind.JAXBException - with linked exception: [java.lang.SecurityException: class "org.eclipse.persistence.jaxb.dynamic.metadata.Metadata"'s signer information does not match signer information of other classes in the same package]"Arathorn
A
39

it´s because java version if you are using jdk 9 or a later version just add this to your pom

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
Appendicectomy answered 29/10, 2018 at 6:34 Comment(4)
I run into this all the time with the Spring Boot guides... Thanks a ton.Hadley
@Cesar Rodriguez T, I tried this with a swagger example and compiling worked but running gave errors. I used the selected answer which included more dependencies and that worked.Halftrack
On pom.xml file of your projectAppendicectomy
In my project two pom.xml i found but they not writable , its only in readable format what i need to do? @CesarRodriguezHubie
C
32

To solve this, I have imported some JAR files in my project:

  • javax.activation-1.2.0.jar

http://search.maven.org/remotecontent?filepath=com/sun/activation/javax.activation/1.2.0/javax.activation-1.2.0.jar

  • jaxb-api-2.3.0.jar

http://search.maven.org/remotecontent?filepath=javax/xml/bind/jaxb-api/2.3.0/jaxb-api-2.3.0.jar

  • jaxb-core-2.3.0.jar

http://search.maven.org/remotecontent?filepath=com/sun/xml/bind/jaxb-core/2.3.0/jaxb-core-2.3.0.jar

  • jaxb-impl-2.3.0.jar

http://search.maven.org/remotecontent?filepath=com/sun/xml/bind/jaxb-impl/2.3.0/jaxb-impl-2.3.0.jar

  1. Download above files and copy them into libs folder in the project
  2. Add the imported JAR files in Java Build Path
Connelly answered 23/1, 2018 at 14:53 Comment(4)
Note that the com.sun.xml.bind artifacts are old and provided only for backward compatibility. You should use the equivalent org.glassfish.jaxb artifacts instead, as mentioned in some of the other answers.Jadda
This didn't work for me. It threw an error, and said that it couldn't find a particular class.Indium
Worked for me when I put them in tomcat9/lib folder under Mint 19.2 (Ubuntu 18.04 base), when deploying a Grails 3.4.10 application.Auric
Didn't work, instead raised more errors requiring several other jar inclusions. Mine was for jdk8Labarbera
L
20

At the time of compilation as well as run time, add the switch --add-modules java.xml.bind

javac --add-modules java.xml.bind <java file name>

java --add-modules java.xml.bind <class file>

A good introduction of the JDK 9 modules can also be found at : https://www.youtube.com/watch?v=KZfbRuvv5qc

Latifundium answered 25/4, 2017 at 4:35 Comment(0)
H
18

I encountered this issue when working on a Java Project in Debian 10.

Each time I start the appliction it throws the error in the log file:

java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

Here's how I solved it:

The issue is often caused when JAXB library (Java Architecture for XML Binding) is missing in the classpath. JAXB is included in Java SE 10 or older, but it is removed from Java SE from Java 11 or newer –moved to Java EE under Jakarta EE project.

So, I checked my Java version using:

java --version

And it gave me this output

openjdk 11.0.8 2020-07-14
OpenJDK Runtime Environment (build 11.0.8+10-post-Debian-1deb10u1)
OpenJDK 64-Bit Server VM (build 11.0.8+10-post-Debian-1deb10u1, mixed mode, sharing)

So I was encountering the JAXBException error because I was using Java 11, which does not have the JAXB library (Java Architecture for XML Binding) is missing in the classpath. JAXB is included in it.

To fix the issue I had to add the JAXB API library to the lib (/opt/tomcat/lib) directory of my tomcat installation:

sudo wget https://repo1.maven.org/maven2/javax/xml/bind/jaxb-api/2.4.0-b180830.0359/jaxb-api-2.4.0-b180830.0359.jar

Then I renamed it from jaxb-api-2.4.0-b180830.0359.jar to jaxb-api.jar:

sudo mv jaxb-api-2.4.0-b180830.0359.jar jaxb-api.jar

Note: Ensure that you change the permission allow tomcat access the file and also change the ownership to tomcat:

sudo chown -R tomcat:tomcat /opt/tomcat
sudo chmod -R 777 /opt/tomcat/

And then I restarted the tomcat server:

sudo systemctl restart tomcat

Resources: [Solved] java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

That's all.

Hyponitrite answered 6/10, 2020 at 8:45 Comment(0)
M
15

I also stumpled accross the ClassNotFoundException:javax.xml.bind.DatatypeConverter using Java 11 and

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

I tried all this stuff around adding javax.xml.bind:jaxb-api or spring boot jakarta.xml.bind-api .. I found a hint for fixes in jjwt version 0.10.0 .. but most importantly, the jjwt package is now split !

Thus, check this reference: https://github.com/jwtk/jjwt/issues/510

Simply, if you use

Java11 and jjwt 0.9.x and you face the ClassNotFoundException:javax.xml.bind.DatatypeConverter issue,

go for

jjwt version 0.11.x, but use the splitted packages: https://github.com/jwtk/jjwt#install

You maven wont find a higher version for jjwt dependency, since they split the packages.

Cheers.

Malignity answered 3/4, 2020 at 9:32 Comment(1)
Using jjwt from io.jsonwebtoken version 0.9.1 with java 16 also caused the same error. The root cause is the same of java 11. Using jjwt-api and jjwt-impl (from io.jsonwebtoken) with version 0.10.7 solved the issue here.Germinate
N
14

Update April 2019

Changelong for JAXB releases is at https://javaee.github.io/jaxb-v2/doc/user-guide/ch02.html

excerpts:

    4.1. Changes between 2.3.0.1 and 2.4.0

         JAXB RI is now JPMS modularized:

            All modules have native module descriptor.

            Removed jaxb-core module, which caused split package issue on JPMS.

            RI binary bundle now has single jar per dependency instead of shaded fat jars.

            Removed runtime class weaving optimization.

    4.2. Changes between 2.3.0 and 2.3.0.1

          Removed legacy technology dependencies:

            com.sun.xml.bind:jaxb1-impl

            net.java.dev.msv:msv-core

            net.java.dev.msv:xsdlib

            com.sun.xml.bind.jaxb:isorelax

    4.3. Changes between 2.2.11 and 2.3.0

          Adopt Java SE 9:

            JAXB api can now be loaded as a module.

            JAXB RI is able to run on Java SE 9 from the classpath.

            Addes support for java.util.ServiceLoader mechanism.

            Security fixes

Authoritative link is at https://github.com/eclipse-ee4j/jaxb-ri#maven-artifacts

Maven coordinates for JAXB artifacts

jakarta.xml.bind:jakarta.xml.bind-api: API classes for JAXB. Required to compile against JAXB.

org.glassfish.jaxb:jaxb-runtime: Implementation of JAXB, runtime used for serialization and deserialization java objects to/from xml.

JAXB fat-jar bundles:

com.sun.xml.bind:jaxb-impl: JAXB runtime fat jar.

In contrast to org.glassfish.jaxb artifacts, these jars have all dependency classes included inside. These artifacts does not contain JPMS module descriptors. In Maven projects org.glassfish.jaxb artifacts are supposed to be used instead.

org.glassfish.jaxb:jaxb-runtime:jar:2.3.2 pulls in:

[INFO] +- org.glassfish.jaxb:jaxb-runtime:jar:2.3.2:compile
[INFO] |  +- jakarta.xml.bind:jakarta.xml.bind-api:jar:2.3.2:compile
[INFO] |  +- org.glassfish.jaxb:txw2:jar:2.3.2:compile
[INFO] |  +- com.sun.istack:istack-commons-runtime:jar:3.0.8:compile
[INFO] |  +- org.jvnet.staxex:stax-ex:jar:1.8.1:compile
[INFO] |  +- com.sun.xml.fastinfoset:FastInfoset:jar:1.2.16:compile
[INFO] |  \- jakarta.activation:jakarta.activation-api:jar:1.2.1:compile

Original Answer

Following Which artifacts should I use for JAXB RI in my Maven project? in Maven, you can use a profile like:

<profile>
    <id>java-9</id>
    <activation>
        <jdk>9</jdk>
    </activation>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>
</profile> 

Dependency tree shows:

[INFO] +- org.glassfish.jaxb:jaxb-runtime:jar:2.3.0:compile
[INFO] |  +- org.glassfish.jaxb:jaxb-core:jar:2.3.0:compile
[INFO] |  |  +- javax.xml.bind:jaxb-api:jar:2.3.0:compile
[INFO] |  |  +- org.glassfish.jaxb:txw2:jar:2.3.0:compile
[INFO] |  |  \- com.sun.istack:istack-commons-runtime:jar:3.0.5:compile
[INFO] |  +- org.jvnet.staxex:stax-ex:jar:1.7.8:compile
[INFO] |  \- com.sun.xml.fastinfoset:FastInfoset:jar:1.2.13:compile
[INFO] \- javax.activation:activation:jar:1.1.1:compile

To use this in Eclipse, say Oxygen.3a Release (4.7.3a) or later, Ctrl-Alt-P, or right-click on the project, Maven, then select the profile.

Nahshunn answered 6/5, 2018 at 3:19 Comment(1)
Thanks for showing that a dependency for javax.xml.bind > jaxb-api that I have seen elsewhere is actually redundant. The glassfish dependency pulls it is. I just tried that, and it does indeed work.Borough
C
14

You need to add JAX-B dependencies when using JDK 9+. For Android Studio user, you'll need to add this to your build.gradle's dependencies {} block:

// Add missing dependencies for JDK 9+
if (JavaVersion.current().ordinal() >= JavaVersion.VERSION_1_9.ordinal()) {
    // If you're using @AutoValue or any libs that requires javax.annotation (like Dagger)
    compileOnly 'com.github.pengrad:jdk9-deps:1.0'
    compileOnly 'javax.annotation:javax.annotation-api:1.3.2'

    // If you're using Kotlin
    kapt "com.sun.xml.bind:jaxb-core:2.3.0.1"
    kapt "javax.xml.bind:jaxb-api:2.3.1"
    kapt "com.sun.xml.bind:jaxb-impl:2.3.2"

    // If you're using Java
    annotationProcessor "com.sun.xml.bind:jaxb-core:2.3.0.1"
    annotationProcessor "javax.xml.bind:jaxb-api:2.3.1"

    testAnnotationProcessor "com.sun.xml.bind:jaxb-core:2.3.0.1"
    testAnnotationProcessor "javax.xml.bind:jaxb-api:2.3.1"
}
Cl answered 6/2, 2020 at 3:7 Comment(3)
I have modified your answer to work with Unit tests as well.Carleycarli
This is the only solution that worked for me!Allyson
This is the best solution!!!Litta
P
13

This worked for me. Adding only jaxb-api wasn't enough.

        <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>
Parrakeet answered 4/12, 2017 at 18:24 Comment(3)
And what was jaxb-api.version set to?Durer
@Durer I used 2.2.7Parrakeet
Note that the com.sun.xml.bind artifacts are old and provided only for backward compatibility. You should use the equivalent org.glassfish.jaxb artifacts instead, as mentioned in some of the other answers.Jadda
E
13

The root cause of this issue is that Gradle Daemon using JDK11, either you set your JAVA_HOME to JDK11 or your running your Gradle Task in the shared daemon which running with JDK11.

For Android:

  1. Check your Project Structure settings, you can change the JDK to JDK8 from there.

  2. You can also set a JAVA_HOME and points to java8 home.

Encephalograph answered 6/5, 2021 at 5:9 Comment(0)
R
12

You can use --add-modules=java.xml.bind JVM option to add xml bind module to JVM run-time environment.

Eg: java --add-modules=java.xml.bind XmlTestClass

Rhone answered 10/10, 2017 at 19:27 Comment(0)
G
12

Go to Your Build.gradle and add below dependencies for both Java 9 or 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'
Geographical answered 8/7, 2018 at 18:51 Comment(0)
S
9

For Java Web Start Execution we can use Andy Guibert's suggestion like this:

<j2se version="1.6+" 
      java-vm-args="-XX:+IgnoreUnrecognizedVMOptions --add-modules=java.se.ee"/>

Note the extra "=" in the --add-modules. See this OpenJDK Ticket or the last note in "Understanding Runtime Access Warnings" of the Java Platform, Standard Edition Oracle JDK 9 Migration Guide.

Severini answered 29/9, 2017 at 8:34 Comment(0)
I
9

add javax.xml.bind dependency in pom.xml

    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>
Imidazole answered 17/10, 2018 at 19:2 Comment(0)
H
9

This solved my problems with dependencies running Apache Camel 2.24.1 on Java 12:

    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>

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

    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-core</artifactId>
        <version>2.3.0.1</version>
    </dependency>

    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.0.1</version>
    </dependency>
Houston answered 25/8, 2019 at 6:32 Comment(1)
in my case i need to add tomcat dependency in pom fileBoman
R
9

Adding the below dependency worked for me.

        <!-- API, java.xml.bind module -->
    <dependency>
        <groupId>jakarta.xml.bind</groupId>
        <artifactId>jakarta.xml.bind-api</artifactId>
        <version>2.3.2</version>
    </dependency>

    <!-- Runtime, com.sun.xml.bind module -->
    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-runtime</artifactId>
        <version>2.3.2</version>
    </dependency>
Retard answered 25/4, 2021 at 5:21 Comment(1)
Make a note that javax libraries are deprecated since jdk 11. Just replace javax dependencies with Jakarta libraries dependencies referring below link. wiki.eclipse.org/Jakarta_EE_Maven_CoordinatesSignory
D
8

Since JavaEE is now governed by https://jakarta.ee/, the new Maven coordinates as of 2.3.2 are:

https://eclipse-ee4j.github.io/jaxb-ri/#maven-artifacts

The first released jaxb.version is 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>
Dor answered 11/4, 2019 at 6:55 Comment(0)
P
7

I followed this URL and the below settings had really helped me. I use Java 10 with STS IDE in Macbook Pro. It works like a charm.

   <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>
Phail answered 15/9, 2018 at 16:12 Comment(0)
D
6

Not an answer, but an addendum: I got because running groovysh (Groovy 2.4.13) if JAVA_HOME points to a Java 9 installation (java version "9.0.1" to be precise) fails abysmally:

java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:107)
        at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:129)
Caused by: java.lang.NoClassDefFoundError: Unable to load class groovy.xml.jaxb.JaxbGroovyMethods due to missing dependency javax/xml/bind/JAXBContext
        at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:400)
        at org.codehaus.groovy.ast.ClassNode.lazyClassInit(ClassNode.java:277)
        at org.codehaus.groovy.ast.ClassNode.getMethods(ClassNode.java:397)
        ...
        ..
        .
        ..
        ...
        at org.codehaus.groovy.tools.shell.Groovysh.<init>(Groovysh.groovy:135)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:232)
        at org.codehaus.groovy.tools.shell.Main.<init>(Main.groovy:66)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:232)
        at org.codehaus.groovy.tools.shell.Main.main(Main.groovy:163)
... 6 more

The solution was to:

  • Go to the JAXB Project at github.io ("JAXB is licensed under a dual license - CDDL 1.1 and GPL 2.0 with Class-path Exception")

  • Download jaxb-ri-2.3.0.zip

  • Unzip wherever you put your java infrastructure files (in my case, /usr/local/java/jaxb-ri/). Other solution may exist (maybe via SDKMAN, I dunno)

  • Make sure the jars in the lib subdirectory are on the CLASSPATH. I do it via a script started on bash startup, called /etc/profile.d/java.sh, where I added (among many other lines) the following loop:

Packed into a function...

function extend_qzminynshg {
   local BASE="/usr/local/java"
   for LIB in jaxb-api.jar  jaxb-core.jar  jaxb-impl.jar  jaxb-jxc.jar  jaxb-xjc.jar; do
      local FQLIB="$BASE/jaxb-ri/lib/$LIB"
      if [[ -f $FQLIB ]]; then
         export CLASSPATH=$FQLIB:$CLASSPATH
      fi
    done
}

extend_qzminynshg; unset extend_qzminynshg

And it works!

Drusilladrusus answered 4/1, 2018 at 20:46 Comment(2)
I don't understand the downvotzes. Apparently people want to faff around with command-line options instead of actually getting the jars? Suit yourself.Drusilladrusus
Java developers typically use build tools like Gradle or Maven to manage dependencies rather than manually downloading jars. That is probably the reason for the down votes.Handcrafted
I
6

I encountered the same issue using Spring Boot 2.0.5.RELEASE on Java 11.

Adding javax.xml.bind:jaxb-api:2.3.0 alone did not fix the problem. I also had to update Spring Boot to the latest Milestone 2.1.0.M2, so I assume this will be fixed in the next official release.

Ice answered 29/9, 2018 at 4:25 Comment(2)
This does not sound related to me. there are several solutions in this thread that work regardless of using spring boot 2. (I also use spring boot 2.0.5.RELEASE btw). Maybe in Spring 2.1.0.M2 there is already a jaxb runtime included.Pledget
It seems that with Spring Boot 2.1.0.RELEASE, JAXB is not necessary anymore - github.com/spring-projects/spring-boot/releasesRome
I
6

As the official documentation states:

When upgrading you may face the following:

java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

Hibernate typically requires JAXB that’s no longer provided by default. You can add the java.xml.bind module to restore this functionality with Java9 or Java10 (even if the module is deprecated).

As of Java11, the module is not available so your only option is to add the JAXB RI (you can do that as of Java9 in place of adding the java.xml.bind module:


Maven

<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
</dependency>

Gradle (build.gradle.kts):

implementation("org.glassfish.jaxb:jaxb-runtime")

Gradle (build.gradle)

implementation 'org.glassfish.jaxb:jaxb-runtime'

If you rather specify a specific version, take a look here: https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime

Intwine answered 11/7, 2020 at 15:40 Comment(0)
P
6

you can use this dependency

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>
Polka answered 20/12, 2021 at 6:44 Comment(5)
where I add thisHubie
you can add this in pom.xml filePolka
where is this pom.xml file , is I need to create new one @AkashKumarSahooHubie
@SurajkaranMeghwanshi if you are creating a maven project you would have pom.xml in the project foulderPolka
its gone 1 year, but thanks for reply. @AkashKumarSahooHubie
C
5

If you are using JDK 11, you can just add the following to your Gradle(app):

dependencies {
    ...
    annotationProcessor "javax.xml.bind:jaxb-api:2.3.1"
    ...
}

It works for me.

Ceruse answered 27/5, 2022 at 9:28 Comment(1)
ya, this allows us to forget this JAXB , but in some cases seems some elements can not found after this change . ex: class file for android.view.ViewGroup not foundSaponify
B
4

OK, I have been having the same kind of issue, but I was using Java 8, and kept getting this error, I tried most of the solutions. but it turns out that my maven was still pointing to java 9 even-though I set the global Java version to 8, as soon as I fixed that it all worked.

For anybody who might have this kind of problem, check out How to fix Maven to use default Java (archived)

Beside answered 22/2, 2018 at 11:39 Comment(1)
The link is deadManamanacle
L
4

You only need 1 dependency:

dependencies {
    implementation ("jakarta.xml.bind:jakarta.xml.bind-api:2.3.2")
Leschen answered 18/2, 2020 at 11:13 Comment(1)
not worked still showing same errorHubie
S
3

For me in Java 11 and gradle this is what worked out:

plugins {
      id 'java'
}

dependencies {
      runtimeOnly 'javax.xml.bind:jaxb-api:2.3.1'
}
Steffens answered 22/8, 2019 at 7:8 Comment(2)
where exactly do we put that?Gertudegerty
In your build.gradle file if you are using gradle.Steffens
D
3

i want to give a simple and easy solution about this Exception , just downgrade the android studio version upto 4.1.1 or less. Make sure you don't have android studio arctic fox (2020.3.1) version , because latest version don't support old project of android.

Doomsday answered 11/8, 2021 at 5:26 Comment(1)
What steps to upgrade to latest Android studio ?Airing
S
3

If you are using JDK 8 above, follow this steps:

  1. Add javax.xml.bind dependency
<dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
</dependency>
  1. clean maven
  2. install maven
Subcontraoctave answered 3/2, 2023 at 9:19 Comment(0)
C
2

Old answer "Problem resolved by switching to amazoncorretto" News answer: I used corretto latest , but is similar jdk 1.8. so anyway we need add dependencies manually

Crowson answered 22/4, 2019 at 7:48 Comment(3)
The Amazon Corretto distribution for JDK 11 does not provide javax.xml.bind classes. If the problem was resolved after switching to Correto, it was because you downgraded to JDK 8.Epanodos
strange, i will check, in the docker i used correto latestCrowson
Yea, amazoncorretto:latest currently gives JDK 8, not 11. Many Docker images are still based on JDK 8, precisely because of the compatibility issues caused by the API removal between JDK 8 --> 11Epanodos
H
2

The dependency versions that I needed to use when compiling for Java 8 target. Tested application in Java 8, 11, and 12 JREs.

        <!-- replace dependencies that have been removed from JRE's starting with Java v11 -->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>2.2.8-b01</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.2.8-b01</version>
        </dependency>
        <!-- end replace dependencies that have been removed from JRE's starting with Java v11 -->
Horta answered 8/6, 2019 at 20:1 Comment(0)
A
2

You need to add jaxb dependancies to maven. The glassfish implementation version 2.3.2 is perfectly compatible with new jakarta EE jaxb api version 2.3.2.

<!-- API -->
<dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>2.3.2</version>
</dependency>

<!-- Runtime -->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.2</version>
</dependency>
Artichoke answered 24/8, 2019 at 14:23 Comment(0)
L
1

I know I'm late to the party, but my error ended up needing a diffrent solution... super simple too

I originally depoloyed to Tomcat 9 and realised I needed 7... I forgot to map my class path back to the 7 version in build.xml

Hopefully this will fix someone elses error in the future, who manages to overlook this simple issue as I did!

Longshore answered 26/10, 2018 at 19:37 Comment(1)
While this may help OP, it's better to add more details, examples, etc.Morales
F
1

i had similar issues after upgrading my project to java 11, then what fixed it was upgrading to spring boot 2.1.1 which apparently has support for java 11, this helped

Fraley answered 19/10, 2019 at 10:44 Comment(1)
please consider adding at least the part of the solution in your answer since link-only answers will become invalid if the url changes in the future.Delogu
U
1

Solution for SBT

libraryDependencies += "javax.xml.bind" % "jaxb-api" % "2.3.1"
Unwary answered 25/10, 2019 at 6:11 Comment(0)
E
1

For me, Eclipse 2020-12 (4.18.0) was using inbuild (org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_15.0.1.v20201027-0507\jre)

upon updating java to 1.8 in installed JREs (which I wanted) resolved the issue.

Hope it helps.

Exhibit answered 24/8, 2022 at 13:48 Comment(1)
This helped me for building java 8 maven projects in eclipse. No need of passing var args in case of java 17,Bedbug
S
1

If you are working with version 3 of spring boot you can downgrade to 2.7.7 and change all jakarta to javax It worked for me

Skew answered 10/3, 2023 at 2:39 Comment(0)
S
0

This worked for me, I have an spring boot project that compiles in Java 8 but I don't know why one day my maven started compiling with Java 11, in Ubuntu I used to fix it:

sudo update-java-alternatives  -l

That showed me the availave JDK on my pc:

java-1.11.0-openjdk-amd64      1111       /usr/lib/jvm/java-1.11.0-openjdk-amd64
java-1.8.0-openjdk-amd64       1081       /usr/lib/jvm/java-1.8.0-openjdk-amd64`

So I finally run this command to choose the desired one:

sudo update-java-alternatives  -s java-1.8.0-openjdk-amd64 

And that's it, for more into take a look at How to use the command update alternatives

Sparing answered 4/6, 2019 at 11:27 Comment(1)
your answer does not respond the question, you just change your path to use java8, meanwhile the question is how to solved with java9Limn
J
0

If you are calling SOAP web services (for example, using jaxws-maven-plugin) just by adding this dependency all JAXB errors disappear:

<dependency>
            <groupId>org.glassfish.metro</groupId>
            <artifactId>webservices-rt</artifactId>
            <version>2.4.3</version>
</dependency>

Tested with Java 13

Jara answered 20/9, 2019 at 15:46 Comment(0)
C
0

For me its simple solution (Mac User)

  run in terminal -->   alias j8="export JAVA_HOME=`/usr/libexec/java_home -v 1.8`;java -version"

then run -->          j8

thats it !!(now run your mvn commands)

Or you can set above in your .bash_profile

Capitular answered 11/2, 2021 at 3:21 Comment(0)
U
0

I have faced same problem in App in which module level build.gradle have added both View Binding and Data Binding.

Earlier

viewBinding {
    enabled = true
}

dataBinding {
    enabled = true
}

Resolved

dataBinding {
    enabled = true
}

In project-level build.gradle used as below

classpath 'com.android.tools.build:gradle:3.6.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"
Urdu answered 25/8, 2021 at 21:13 Comment(0)
G
0

I am using these dependency and working perfectly

enter code h<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.1</version>
    </dependency>
</dependencies>ere
Giffin answered 11/4, 2023 at 11:5 Comment(0)
B
0

Update, 2024

New Questions are being closed as duplicates of this one. While I hate to add another Answer to this long page, (a) most of these Answers are a bit old, and (b) most of these Answers are either terse or confusing. So, I will give it a shot.

tl;dr

  • Obtain JARs for both API and implementation of Jakarta XML Binding specification.
  • May or may not need to bundle with your final app.

Java EE is no more, long live Java EE

Understand that in recent years, Oracle Corp donated the Java EE technologies to the Eclipse Foundation. Oracle retains possession of the Java™ trademark. The new name became Jakarta EE.

By the way, in the Jakarta era, the acronyms like JAXB are discouraged. Use the newly shortened names instead.

Jakarta EE — specification & implementation

Jakarta XML Binding (formerly Java Architecture for XML Binding, JAXB) is a specification, found here. A Java JAR provides the interfaces (API) through which you will interact with an implementation of those specs.

An implementation was bundled with Java SE through Java 10. Java SE versions 11 and later come without the API, and without an implementation.

If you deploy to a Jakarta EE compliant app server, then you may find both the API and the implementation bundled there. If that is the case, you should not bundle either with your app.

If you deploy to a desktop app or a console app via Java SE 11 and later, you must bundle both the API and an implementation.

Know that you can skip the Jakarta XML Binding API, and instead call directly the methods defined in the implementation. But doing so means you give up the flexibility to swap out implementations without rewriting your app.

For the API, the open-source project is hosted here. Find the Maven coordinates for download at a Maven repository such as this. For example:

<!-- https://mvnrepository.com/artifact/jakarta.xml.bind/jakarta.xml.bind-api -->
<dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>4.0.1</version>
</dependency>

One implementation has the unimaginative name of Eclipse Implementation of JAXB™. The open-source project is hosted here. Find its Maven coordinates for download at a Maven repository such as this. For example:

<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>4.0.4</version>
</dependency>

(The com.sun naming dates back to when Sun Microsystems invented Java SE and Java EE.)

Related libraries are transitively pulled in.

  • Dependencies
    • jakarta.xml.bind:jakarta.xml.bind-api:4.0.1
      • jakarta.activation:jakarta.activation-api:2.1.2
    • com.sun.xml.bind:jaxb-impl:4.0.4
      • com.sun.xml.bind:jaxb-core:4.0.4
        • jakarta.xml.bind:jakarta.xml.bind-api:4.0.1 (duplicate omitted)
        • org.eclipse.angus:angus-activation:2.0.1
          • jakarta.activation:jakarta.activation-api:2.1.2 (duplicate omitted)

Another implementation is EclipseLink MOXy.

<!-- https://mvnrepository.com/artifact/org.eclipse.persistence/org.eclipse.persistence.moxy -->
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.moxy</artifactId>
    <version>4.0.2</version>
</dependency>

In the example app below, I did swap out these two implementations just by changing the dependency element of the POM — and it worked swimmingly!

I asked here for any other implementations.

Excluding a dependency

If you do not need to bundle the API & implementation in your final app artifact, add a <scope> element to the <dependency> elements seen above. See the documentation, this tutorial, and this Question.

Example app

Here is an example app. This app performs both import and export of an XML file, going through Jakarta XML Binding in both directions. This example is my modified version of an example app seen in the post JAXB (with Java 11) - Tutorial by Lars Vogel.

We start a new project with Maven archetype Quickstart. I modified the default Maven POM to utilize the latest versions.

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>work.basil.example</groupId>
    <artifactId>ExJakartaXmlBinding</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>ExJakartaXmlBinding</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.release>22</maven.compiler.release>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.10.2</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/jakarta.xml.bind/jakarta.xml.bind-api -->
        <dependency>
            <groupId>jakarta.xml.bind</groupId>
            <artifactId>jakarta.xml.bind-api</artifactId>
            <version>4.0.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>4.0.4</version>
        </dependency>

        <!--        &lt;!&ndash; https://mvnrepository.com/artifact/org.eclipse.persistence/org.eclipse.persistence.moxy &ndash;&gt;-->
        <!--        <dependency>-->
        <!--            <groupId>org.eclipse.persistence</groupId>-->
        <!--            <artifactId>org.eclipse.persistence.moxy</artifactId>-->
        <!--            <version>4.0.2</version>-->
        <!--        </dependency>-->

    </dependencies>

    <build>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.3.2</version>
                </plugin>
                <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.3.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.11.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.1.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.3.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>3.1.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>3.1.1</version>
                </plugin>
                <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
                <plugin>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>4.0.0-M9</version>
                </plugin>
                <plugin>
                    <artifactId>maven-project-info-reports-plugin</artifactId>
                    <version>3.5.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

Define a class Book as our business domain model.

package work.basil.example;

import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;

@XmlRootElement ( name = "book" )
@XmlType ( propOrder = { "author" , "name" , "publisher" , "isbn" } )  // Order of the properties.
public class Book
{
    private String name;
    private String author;
    private String publisher;
    private String isbn;

    @XmlElement ( name = "title" )  // Optional override of property identifier.
    public String getName ( ) { return name; }

    public void setName ( String name ) { this.name = name; }

    public String getAuthor ( ) { return author; }

    public void setAuthor ( String author ) { this.author = author; }

    public String getPublisher ( ) { return publisher; }

    public void setPublisher ( String publisher ) { this.publisher = publisher; }

    public String getIsbn ( ) { return isbn; }

    public void setIsbn ( String isbn ) { this.isbn = isbn; }
}

We keep instances of Book in a Bookstore, as a hierarchy.

package work.basil.example;

import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementWrapper;
import jakarta.xml.bind.annotation.XmlRootElement;

import java.util.Collection;
import java.util.List;

@XmlRootElement ( namespace = "work.basil.example.model" )
public class Bookstore
{
    // Fields
    @XmlElementWrapper ( name = "bookList" )
    @XmlElement ( name = "book" )
    private Collection < Book > bookList;

    private String name;

    // Mutators
    public void setName ( final String name ) { this.name = name; }

    public void setBookList ( final Collection < Book > bookList ) { this.bookList = List.copyOf( bookList ); }

    // Accessors
    public Collection < Book > getBooksList ( ) { return List.copyOf( bookList ); }

    public String getName ( ) { return name; }
}

Utilize these classes in our main method to export and import XML data in a file.

package work.basil.example;

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;

import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class BookMain
{
    public static void main ( String[] args ) throws JAXBException, IOException
    {
        // Business model.
        Bookstore bookstore = getBookstore( );

        // create JAXB context and instantiate marshaller
        JAXBContext context = JAXBContext.newInstance( Bookstore.class );
        Marshaller m = context.createMarshaller( );
        m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT , Boolean.TRUE );

        // Write to System.out
        m.marshal( bookstore , System.out );

        // Write to File
        final Path path = Files.createTempFile( "bookstore-jaxb" , "xml" );
        m.marshal( bookstore , path.toFile( ) );

        // Extract from our XML file.
        System.out.println( );
        System.out.println( "Output from our XML file: " );
        Unmarshaller um = context.createUnmarshaller( );
        Bookstore bookstore2 = ( Bookstore ) um.unmarshal( new FileReader( path.toFile( ) ) );
        Collection < Book > books = bookstore2.getBooksList( );
        for ( Book book : books )
        {
            System.out.println( "Book: " + book.getName( ) + " from " + book.getAuthor( ) );
        }
    }

    private static Bookstore getBookstore ( )
    {
        Collection < Book > bookList = new ArrayList < Book >( );

        // create books
        var book1 = new Book( );
        book1.setIsbn( "9781491910771" );
        book1.setName( "Head First Java, 3rd Edition" );
        book1.setAuthor( "Kathy Sierra, Bert Bates, Trisha Gee" );
        book1.setPublisher( "O'Reilly Media, Inc." );
        bookList.add( book1 );

        var book2 = new Book( );
        book2.setIsbn( "1-55750-446-6" );
        book2.setName( "The Sand Pebbles" );
        book2.setAuthor( "Richard McKenna" );
        book2.setPublisher( "Harper & Row" );
        bookList.add( book2 );

        // create bookstore, assigning book
        var bookstore = new Bookstore( );
        bookstore.setName( "Third Place Books" );
        bookstore.setBookList( List.copyOf( bookList ) );

        return bookstore;
    }
}

When run:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:bookstore xmlns:ns2="work.basil.example.model">
    <bookList>
        <book>
            <author>Kathy Sierra, Bert Bates, Trisha Gee</author>
            <title>Head First Java, 3rd Edition</title>
            <publisher>O'Reilly Media, Inc.</publisher>
            <isbn>9781491910771</isbn>
        </book>
        <book>
            <author>Richard McKenna</author>
            <title>The Sand Pebbles</title>
            <publisher>Harper &amp; Row</publisher>
            <isbn>1-55750-446-6</isbn>
        </book>
    </bookList>
    <name>Third Place Books</name>
</ns2:bookstore>

Output from our XML file: 
Book: Head First Java, 3rd Edition from Kathy Sierra, Bert Bates, Trisha Gee
Book: The Sand Pebbles from Richard McKenna
Borough answered 27/2, 2024 at 5:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.