Search code examples
javajava-module

Java Modules - Adding modules, but not everything from it?


I have a simple Spring Boot application, described here

Java Modules - Simple Spring Boot application, create custom runtime

which isn't a modularized application (no module-info.java).

As described in that post, when creating a custom runtime image, to make that simple application run, I have to add the java.desktop module.

jlink --module-path $JAVA_HOME/jmods --add-modules java.desktop --output mycustomrt

When a module is added, must always the whole module be added, or can it be further reduced to just the needed/used packages (artifacts)?

Of course in that given command there is no direct association to my simple application, so it would be logical that the whole java.desktop module is included, also it's transitive declared modules.

But looking into the documentation at

https://docs.oracle.com/en/java/javase/19/docs/api/java.desktop/module-summary.html

I see, that java.desktop contains a lot of packages that my simple application doesn't need

exports java.applet
exports java.awt
exports java.awt.color
exports java.awt.desktop
exports java.awt.dnd
exports java.awt.event
exports java.awt.font
exports java.awt.geom
exports java.awt.im
exports java.awt.im.spi
exports java.awt.image
exports java.awt.image.renderable
exports java.awt.print
exports java.beans
exports java.beans.beancontext
exports javax.accessibility
exports javax.imageio
exports javax.imageio.event
exports javax.imageio.metadata
exports javax.imageio.plugins.bmp
exports javax.imageio.plugins.jpeg
exports javax.imageio.plugins.tiff
exports javax.imageio.spi
exports javax.imageio.stream
exports javax.print
exports javax.print.attribute
exports javax.print.attribute.standard
exports javax.print.event
exports javax.sound.midi
exports javax.sound.midi.spi
exports javax.sound.sampled
exports javax.sound.sampled.spi
exports javax.swing
exports javax.swing.border
exports javax.swing.colorchooser
exports javax.swing.event
exports javax.swing.filechooser
exports javax.swing.plaf
exports javax.swing.plaf.basic
exports javax.swing.plaf.metal
exports javax.swing.plaf.multi
exports javax.swing.plaf.nimbus
exports javax.swing.plaf.synth
exports javax.swing.table
exports javax.swing.text
exports javax.swing.text.html
exports javax.swing.text.html.parser
exports javax.swing.text.rtf
exports javax.swing.tree
exports javax.swing.undo

Applet, AWT, Swing, also something regarding sound, which definitely isn't needed.


Solution

  • Yes, only the whole module can be added with the requires clause. This is necessary to deliver the reliable configuration provided by the module system. If you were able to exclude some packages at will, you could get errors at runtime reporting missing classes because the packages were actually needed.

    If you want to trim the size of your image further, you could look into ahead-of-time compilation offered by GraalVM, which has a "tree-shaking" aspect to it.