On this page
Maven Plugin
1 Overview
Maven plugin to execute and package Micronaut applications.
This plugin has the following features:
-
Packaging an application into different formats: fat JAR, native image, Docker, etc.
-
Deploying Docker images to different registries.
-
Validating Micronaut configuration and dependency injection.
Usage
It is recommended to use this plugin in combination with the Micronaut Parent POM.
Then, declare the plugin to your build/plugins section:
<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">
<!-- ... -->
<packaging>${packaging}</packaging>
<properties>
<!-- ... -->
<packaging>jar</packaging>
<micronaut.runtime>netty</micronaut.runtime>
</properties>
<build>
<plugins>
<!-- ... -->
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>|
Warning
|
Since version 4.0.0 of this plugin (which is the version compatible with Micronaut 4.x), the group id is
io.micronaut.maven. Earlier versions compatible with Micronaut 3.x used io.micronaut.build.
|
The <packaging> part is important since the plugin supports several packaging types. The default is jar.
For snapshot versions, you need the Maven Central Portal Snapshot repository:
<project>
<!-- ... -->
<pluginRepositories>
<!-- ... -->
<pluginRepository>
<id>central-portal-snapshots</id>
<url>https://central.sonatype.com/repository/maven-snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>1.2 Goals
Maven generates this reference from the plugin's goal descriptors when it builds the plugin site. Read Goals on the published Micronaut Maven Plugin site.
To see the release history, check the GitHub Releases page.
2 Examples
It watches for changes in the project tree, and if they match certain conditions, it will recompile and restart the application.
The plugin can handle changes in Java, Groovy and resource source directories by default.
Note that this plugin can work with any Micronaut version (and potentially with any Java application), since it only deals with file changes and JVM restarts.
Usage
You can use mn:run to run your application in development mode:
$ mvn clean mn:run
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------< java.maven.junit:java-maven-junit >------------------
[INFO] Building java-maven-junit 0.1
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ java-maven-junit ---
[INFO] Deleting /Users/alvarosanchez/Micronaut/micronaut-maven-plugin/examples/java/target
[INFO]
[INFO] --- mn:4.0.0:run (default-cli) @ java-maven-junit ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to /Users/alvarosanchez/Micronaut/micronaut-maven-plugin/examples/java/target/classes
13:36:32.665 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 919ms. Server Running: http://localhost:8080Including and excluding options
By default, this plugin watches for changes in the following locations:
-
/pom.xml. Only dependency changes may trigger an application restart. -
src/main/resources/*/. -
src/main/java/*/(if it exists). -
src/main/groovy/*/(if it exists).
You can further include or exclude some other locations:
<project>
<!-- ... -->
<build>
<plugins>
<!-- ... -->
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<version>5.1.0</version>
<configuration>
<watches>
<watch>
<directory>src/main/resources</directory>
<excludes>
<exclude>application-test.yml</exclude>
</excludes>
</watch>
<watch>
<directory>src/main/webapp</directory>
</watch>
</watches>
</configuration>
</plugin>
</plugins>
</build>
</project>Note that exclusions take precedence over inclusions, so if a file change matches both, it will be excluded.
When no includes/excludes rules are specified, a **/* pattern will be included by default.
Debugging
Debugging options can be specified on the command line directly:
-
Running in debug mode:
mvn mn:run -Dmn.debug. -
Changing the debugger port:
mvn mn:run -Dmn.debug -Dmn.debug.port=5006. -
Changing the debugger host:
mvn mn:run -Dmn.debug -Dmn.debug.host=192.168.1.8ormvn mn:run -Dmn.debug -Dmn.debug.host=* -
Suspending the debugger execution:
mn:run -Dmn.debug -Dmn.debug.suspend.
Monitoring with JMX
Since 5.1.0, mn:run no longer adds -Dcom.sun.management.jmxremote to the application’s command line, so the JVM
no longer starts the JMX management agent before main on every start and restart.
Local tools do not need it. JConsole, VisualVM and Java Mission Control attach to the running application and start
the local agent on demand, and jcmd does not use the agent.
To start the agent with the application anyway, for example when the JVM runs with -XX:+DisableAttachMechanism,
pass the property yourself in one of these ways:
-
As a user property, which
mn:runpasses on to the application:mvn mn:run -Dcom.sun.management.jmxremote. -
As a JVM argument:
mvn mn:run -Dmn.jvmArgs=-Dcom.sun.management.jmxremote. -
In the plugin configuration:
<configuration> <jvmArguments>-Dcom.sun.management.jmxremote</jvmArguments> </configuration>
For remote JMX, set com.sun.management.jmxremote.port together with the authentication and SSL properties your
setup needs. The JVM then starts the agent, and -Dcom.sun.management.jmxremote is not needed.
Class data sharing (experimental)
On every launch and restart, the JVM parses, verifies and links the classes of all the dependency JARs again. With
mn.classDataSharing, mn:run keeps those classes in a static
CDS archive, and the launches after the first one
map them from the archive instead:
$ mvn mn:run -Dmn.classDataSharingThe option is experimental: its name, its files and its behaviour may change in a later version. It needs JDK 25 or later
to run the application (the toolchain’s JDK when one is configured). With an older JDK, mn:run logs one line and
launches the application as it does without the option.
What it does and what it costs
-
The first launch records the classes it loads (
-XX:DumpLoadedClassList). When that launch ends, because of a restart, because the application exited with status 0, or because of Ctrl+C,mn:runcreates the archive in the background withjava -Xshare:dumpand checks once that the JVM accepts it. This takes a few seconds. Launches in the meantime run without an archive. After Ctrl+C, the nextmn:runcreates the archive in the background instead, and its first launch runs without it. With-Dmn.watch=false, the goal waits for the archive before it ends. -
The launches and restarts after that get
-XX:SharedArchiveFile=… -Xlog:cds*=off,aot*=off, before the arguments ofmn.jvmArgs. They run no extra check. -
The archive is specific to the JDK build, to the JVM options that decide whether the JVM can use an archive (the
-XX:options, the heap size, the module options and the modules that-Dcom.sun.management…properties, JFR options and Java agents add), and to the path, size and modification time of every dependency JAR. When one of them changes, the next launch records again and the archive is created again. Editing the code or the resources of the project never does. -
mn:runadds no-Dcom.sun.management…property of its own, so the archive leaves out the JMX agent’s module (jdk.management.agent) unless you start the agent as the previous section describes. Turning that on or off records again. -
Everything lives in
target/mn-cds: the archive (about 50 MB for an application with 50 dependency JARs), the recorded class list, the list of the files of the JARs, and the log of the dump.mvn cleandeletes it, somvn clean mn:runrecords again. -
If the JVM cannot create or use the archive,
mn:runlogs one line that names the log file, and launches without an archive until one of the inputs above changes.
The archive works with -Dmn.debug and with Java agents, including the native image agent of -Dagent=true.
Class path order
While the option is on, the class path of every launch is:
-
the dependency JARs, in the usual order;
-
the
target/classesdirectories of the project and of the reactor modules it depends on; -
any other dependency entry, such as a directory.
Without the option, the target/classes directories come first. Only the JARs go into the archive, because the JVM does
not archive classes from directories, so editing the project never invalidates the archive.
Before each launch, mn:run looks up every file of the entries that move after the JARs in the files of the JARs. If a
file exists in both, for example a class, a logback.xml or an application.yml, moving the project after the JARs
would change which copy the application sees. mn:run then logs a warning that names the file and the JAR, and
launches with the usual order and no archive. These files are not compared, because they are merged or describe the
JAR they are in: META-INF/services/, META-INF/micronaut/, META-INF/MANIFEST.MF, module-info.class,
META-INF/versions/, META-INF/maven/, signature files, and licence and notice files.
The check cannot see one consequence of the new order: the merged files of the project (META-INF/micronaut/,
META-INF/services/) are now found after those of the dependencies.
-
Micronaut registers an application bean of a type that a library also provides after the library’s bean, so an injected collection of that type that has no explicit order (
@Order,Ordered) can list its beans in another order. -
A library that takes the first service provider it finds can pick another one.
Checking that the archive is used
Log the class loading of a launch that has the archive. The application runs in the target directory, so the file
below is target/class-load.log:
$ mvn mn:run -Dmn.classDataSharing "-Dmn.jvmArgs=-Xlog:class+load:file=class-load.log"The classes of the dependencies show source: shared objects file, and those of the project show their
target/classes directory.
When the option has no effect
mn:run launches the application as it does without the option, and says why at debug level (-X), when the JVM
options, from mn.jvmArgs or from the JAVA_TOOL_OPTIONS, JDK_JAVA_OPTIONS or _JAVA_OPTIONS environment variables:
-
already decide what CDS or the JDK AOT cache does:
-Xshare:…,-XX:SharedArchiveFile,-XX:SharedClassListFile,-XX:ArchiveClassesAtExit,-XX:+AutoCreateSharedArchive,-XX:DumpLoadedClassList,-XX:AOTCache,-XX:AOTCacheOutput,-XX:AOTMode,-XX:AOTConfigurationor-XX:+AOTClassLinking; -
change the module graph with
--limit-modules,--upgrade-module-path,--patch-moduleor--module-path; -
or read more options from a file (
@argfile,-XX:VMOptionsFile,-XX:Flags).
Other options
For a full list of configuration options, check the mn:run goal documentation.
Collecting native-image metadata during mn:run
mn:run can launch the application with the GraalVM native-image tracing agent by using the same -Dagent=true
switch that org.graalvm.buildtools:native-maven-plugin understands:
$ mvn mn:run -Dagent=true -Dmn.watch=falseThis generates metadata under target/native/agent-output/main.
Use this when you want to exercise the application on the JVM and then feed the collected metadata back into the
upstream native-image workflow. Micronaut still delegates native-image packaging to
org.graalvm.buildtools:native-maven-plugin; mn:run only covers the application-run tracing step.
The initial mn:run integration supports the upstream standard agent mode. Advanced workflows such as direct mode,
conditional mode, and metadata copy orchestration should continue to use the upstream native-build-tools Maven plugin
workflow directly.
This plugin supports different <packaging> types:
-
jar(default): produces a runnable fat JAR. -
native-image: generates a GraalVM native image. -
docker: builds a Docker image with the application artifacts (compiled classes, resources, dependencies, etc). -
docker-native: builds a Docker image with a GraalVM native image inside. -
docker-crac: builds a Docker image containing a CRaC checkpointed application. -
k8s: delegates packaging to Eclipse JKube’s Kubernetes Maven Plugin (k8s:build). -
openshift: delegates packaging to Eclipse JKube’s OpenShift Maven Plugin (oc:build).
To package an application, mvn package is the one-stop shop to produce the desired artifact. By default, applications
generated from Micronaut Launch have the packaging defined like
<packaging>${packaging}</packaging>, so that you can do something like mvn package -Dpackaging=native-image:
Packaging the application in a fat JAR
$ mvn packageIf the <packaging> is set to jar, this plugin will delegate to the maven-shade-plugin to produce a JAR file. Its
configuration is defined in the io.micronaut:micronaut-parent POM, and the defaults should be enough. Should you want
to customize how to produce the JAR file, refer to the
Maven Shade Plugin documentation.
Classpath-sensitive libraries and shaded JARs
Shaded JARs are convenient for single-file deployments, but they are not a good fit for every runtime. Libraries that expect to discover resources, languages, or services from separate classpath entries can fail once everything is merged into one archive. GraalVM Truffle or polyglot language deployments are a common example of this limitation.
For those applications, disable the Shade execution and deploy the application as separate artifacts instead of as a single fat JAR:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>When shading is disabled, prefer one of these deployment models:
-
mvn package -Dpackaging=dockerto build a JVM Docker image with classes, resources, and dependencies kept as separate artifacts instead of as a shaded JAR. -
A custom
Dockerfileor launcher script that starts the application from an explicit classpath.
If you provide your own Dockerfile, Micronaut Maven Plugin prepares the runtime dependencies under
target/dependency, so you can launch the application with a regular classpath instead of java -jar.
For compatibility with existing custom Dockerfiles, the flat target/dependency/* layout is still produced even
though the plugin-managed Dockerfile templates now also stage target/dependency/release/ and
target/dependency/snapshot/ as separate layers:
FROM ...
...
COPY classes /home/app/classes
COPY dependency/* /home/app/libs/
...
ENTRYPOINT ["java", "-cp", "/home/app/libs/*:/home/app/classes/", "com.example.app.Application"]The plugin does not currently provide a dedicated non-shaded launcher for plain jar packaging, so if your runtime
depends on separate classpath entries, prefer docker packaging or your own classpath-based launch script over the
default shaded JAR.
If you intentionally keep a shaded fat JAR for a GraalVM Truffle or GraalPy application, follow the
GraalVM uber-JAR guidance and
make the application POM preserve the multi-release manifest metadata required by Truffle. Configure the Shade plugin
with both the services transformer and a manifest transformer that keeps ${exec.mainClass} as the main class and adds
Multi-Release: true:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>${exec.mainClass}</mainClass>
<manifestEntries>
<Multi-Release>true</Multi-Release>
</manifestEntries>
</transformer>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>Micronaut Maven Plugin does not add this manifest entry for every application because most applications do not need
Truffle’s multi-release metadata. To verify the packaging, inspect META-INF/MANIFEST.MF in the generated JAR and
confirm it contains Multi-Release: true, then start the application with the same JDK used in production. Do not
disable Truffle’s multi-release validation check as a packaging fix.
Generating GraalVM native images
$ mvn package -Dpackaging=native-imageIf the <packaging> is set to native-image, this plugin will delegate to the official Maven plugin for GraalVM Native Image (org.graalvm.buildtools:native-maven-plugin) to generate a native image. Note that for this packaging to work,
you need to run locally a GraalVM JDK.
Refer to the Native Maven Plugin documentation for more information about how to customize the generated native image.
If you want to collect native-image metadata before packaging, you can run the application with
mvn mn:run -Dagent=true -Dmn.watch=false. That generates tracing output in target/native/agent-output/main, which
you can then review or process with the upstream native-build-tools workflow before running
mvn package -Dpackaging=native-image.
For example, to add --verbose to the native image args, you should define:
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<configuration>
<buildArgs combine.children="append">
<buildArg>--verbose</buildArg>
</buildArgs>
</configuration>
</plugin>For GraalVM/Java 25 or newer native images that need Netty’s shared arena support, add
-H:+SharedArenaSupport through the same upstream native plugin <buildArgs> configuration. Micronaut Maven Plugin
does not rewrite the delegated native-image packaging configuration.
Windows users
Sometimes, depending on how many classes are in the classpath you may see an error The command line is too long when
building a native-image. This is a known issue
with Windows. To work around this you need to configure the Shade plugin in your pom.xml and then configure the native image
plugin to use that shaded jar for building the native image:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>shaded</shadedClassifierName>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<configuration combine.self="override">
<mainClass>${exec.mainClass}</mainClass>
<classpath>
<param>${project.build.directory}/${project.artifactId}-${project.version}-shaded.jar</param>
</classpath>
</configuration>
</plugin>Then run:
Building daemonless native executable container images
$ mvn package -Dpackaging=native-image -Dmicronaut.native-image.jib.enabled=trueIf the <packaging> is set to native-image and micronaut.native-image.jib.enabled is set to true, this plugin first delegates to
org.graalvm.buildtools:native-maven-plugin:compile-no-fork to create the local native executable, then packages only
that executable into a container image with Jib Core. This workflow does not require a Docker daemon.
By default, the native image Jib workflow writes the Jib tarball to target/jib-image.tar:
mvn package -Dpackaging=native-image -Dmicronaut.native-image.jib.enabled=trueTo publish directly to a registry without Docker, use Jib’s registry build goal and destination configuration:
mvn package -Dpackaging=native-image -Dmicronaut.native-image.jib.enabled=true -Djib.buildGoal=build -Djib.to.image=my-company/my-app:latestThe supported jib.buildGoal values for the native image Jib workflow are buildTar and build. Use docker-native packaging
when you need Docker-backed native image builds.
The image name, additional tags, and registry credentials use the same Jib configuration keys as JVM docker
packaging, including jib.to.image, jib.to.tags, jib.to.auth.username, jib.to.auth.password, Jib credential
helpers, Google Application Default Credentials, and Docker config credential lookup. The tarball path can be changed
with Jib’s jib.outputPaths.tar setting.
The runtime base image is resolved in this order:
-
jib.from.image -
micronaut.native-image.jib.base-image -
micronaut.native-image.base-image-run -
The Micronaut Maven Plugin native runtime default
The container entrypoint defaults to /app/<executable-name>, the working directory defaults to /app, and the image
copies only the native executable into the runtime layer. Set micronaut.native-image.jib.executable when the native
executable is not at target/<native imageName or artifactId>. Jib container args, ports, user, entrypoint, and platform
configuration are honored where they apply to a single native executable image.
The native image Jib workflow packages a locally built executable into a Linux container image. By default, it fails on non-Linux
hosts and when the host architecture does not match the configured Jib platform, because a macOS or Windows native
executable will not run in a Linux container image. Use docker-native when you need Docker to build the Linux native
executable from another host OS. If you have intentionally cross-compiled a compatible Linux executable, set
micronaut.native-image.jib.allow-platform-mismatch=true.
Lambda and Oracle Function native images keep their existing runtime-specific docker-native packaging paths.
Building JVM-based Docker images
$ mvn package -Dpackaging=dockerIf the <packaging> is set to docker, this plugin will use com.google.cloud.tools:jib-maven-plugin to produce a
Docker image with the application artifacts (compiled classes, resources, dependencies, etc) inside.
The Docker image is built to a local Docker daemon (the equivalent of executing the jib::dockerBuild goal).
If you want daemonless packaging, set -Djib.buildGoal=buildTar to produce the standard Jib tarball at
target/jib-image.tar, or -Djib.buildGoal=build to publish directly to the configured registry during the package
phase. The build goal is also the daemonless path for mvn deploy -Dpackaging=docker: Maven runs package before
deploy, so Jib publishes the image during package and the later deploy step skips the Docker-daemon push.
Depending on the micronaut.runtime property, the image built might be different. Options are:
-
Default runtime:
mvn package -Dpackaging=docker. -
JDK HTTP server runtime (Starter compatibility alias; same Docker image as the default runtime):
mvn package -Dpackaging=docker -Dmicronaut.runtime=http_server_jdk. -
Daemonless tarball:
mvn package -Dpackaging=docker -Djib.buildGoal=buildTar. -
Daemonless registry publish:
mvn package -Dpackaging=docker -Djib.buildGoal=build -Djib.to.image=registry.example.com/team/app:latest. -
Oracle Cloud Function:
mvn package -Dpackaging=docker -Dmicronaut.runtime=oracle_function. -
AWS Lambda (Java runtimes):
mvn package -Dpackaging=docker -Dmicronaut.runtime=lambda.
You can use the mn:dockerfile goal to generate the equivalent Dockerfile. Generated
Dockerfiles copy dependency/release/ and dependency/snapshot/ separately so Docker layer caching can reuse
non-SNAPSHOT dependencies more effectively. For example, to generate the Dockerfile for AWS Lambda, run
mvn mn:dockerfile -Dpackaging=docker -Dmicronaut.runtime=lambda.
Refer to the Jib Maven Plugin documentation to see what are the configuration options that can be used.
For example, you can define the jib-maven-plugin in your POM as follows to pass additional JVM and application args:
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<configuration>
<container>
<jvmFlags>
<jvmFlag>-Dmy.property=example.value</jvmFlag>
<jvmFlag>-Xms512m</jvmFlag>
<jvmFlag>-Xdebug</jvmFlag>
</jvmFlags>
<args>
<arg>some</arg>
<arg>args</arg>
</args>
</container>
</configuration>
</plugin>Training a JDK AOT cache
$ mvn package -Dpackaging=docker -Dmicronaut.docker.jdkAotCache=trueA JDK AOT cache makes the application start faster. The plugin creates the cache by running the application once while it builds the image, and the image starts the application with it. This is independent of Micronaut AOT, and the two can be combined.
It works both with Jib and with mn:dockerfile: with micronaut.docker.jdkAotCache set, the generated Dockerfile
trains the cache during docker build. The cache depends on the garbage collector, so with Jib you must select one in
container.jvmFlags (the generated Dockerfile uses -XX:+UseG1GC):
<properties>
<micronaut.docker.jdkAotCache>true</micronaut.docker.jdkAotCache>
</properties>
...
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<configuration>
<container>
<jvmFlags>
<jvmFlag>-XX:+UseSerialGC</jvmFlag>
</jvmFlags>
</container>
</configuration>
</plugin>| Property | Default | Description |
|---|---|---|
|
|
Trains a JDK AOT cache and starts the application with it. |
|
See below |
|
|
None |
Comma-separated paths that a |
|
|
Timeout of the training run, in seconds. |
Training modes
-
LOAD: the application loads its bean definitions and the classes they use, and exits without starting. The image build does not need the database, message broker or other services that the application uses. -
START: the application starts, answers the training requests and stops. This gives a more complete, and larger, cache, but every service that the application needs at start-up must be reachable from the image build, for example throughdocker.networkMode.
LOAD needs Micronaut Core 5.3.0 or later, where it is the default. Earlier versions train with START. Set START
explicitly to send training requests, or to keep starting the application after you upgrade:
$ mvn package -Dpackaging=docker -Dmicronaut.docker.jdkAotCache=true \
-Dmicronaut.docker.jdkAotCache.trainingMode=START \
-Dmicronaut.docker.jdkAotCache.trainingPaths=/hello,/booksA training request that gets no response or a 5xx response fails the build. So does a 4xx response with Micronaut
Core before 5.3.0; later versions log it as a warning.
Limitations
-
The base image needs Java 25 or later.
-
The training runs in a container, so it needs a Docker daemon, also with
jib.buildGoal=buildTarorbuild. The image is built for the platform of that daemon only. -
The
lambdaandoracle_functionruntimes are not supported. -
With Jib, the option sets
jib.containerizingMode=packaged, and a customcontainer.entrypointis not supported. -
The generated
Dockerfileneedsbashin the base image, and so does Jib with Micronaut Core before 5.3.0. -
With Jib, every build trains a new cache, so every push uploads a new cache layer.
-
If you keep a generated
Dockerfilein your project, generate it again withmn:dockerfileafter you upgrade the plugin.
Delegating packaging to Eclipse JKube
$ mvn package -Dpackaging=k8sThe k8s and openshift packaging types let Micronaut’s lifecycle bindings delegate to Eclipse JKube instead of
the built-in Docker/Jib packaging.
-
k8smapspackagetoorg.eclipse.jkube:kubernetes-maven-plugin:build. -
openshiftmapspackagetoorg.eclipse.jkube:openshift-maven-plugin:build.
These packaging types are additive. They only activate when you explicitly set the packaging, and you must still declare and configure the corresponding JKube plugin in your build. Micronaut does not manage JKube plugin versions or configuration for you.
For example, to use the Kubernetes integration:
<plugin>
<groupId>org.eclipse.jkube</groupId>
<artifactId>kubernetes-maven-plugin</artifactId>
<version>1.19.0</version>
</plugin>Then package with:
mvn package -Dpackaging=k8sFor OpenShift, declare the OpenShift plugin instead:
<plugin>
<groupId>org.eclipse.jkube</groupId>
<artifactId>openshift-maven-plugin</artifactId>
<version>1.19.0</version>
</plugin>and package with:
mvn package -Dpackaging=openshiftBringing your own Dockerfile
$ mvn package -Dpackaging=dockerIf there is a Dockerfile in the project’s root directory, it will be used to build the image. The image will be built
using the target folder as the context directory. This plugin will also prepare all the compile and runtime
dependency JARs in the target/dependency folder. Custom Dockerfiles can continue to use the flat
target/dependency/* layout, while generated Dockerfiles use split dependency/release/ and
dependency/snapshot/ directories for finer-grained image layers. For a custom Dockerfile, you can still do:
FROM ...
...
COPY classes /home/app/classes
COPY dependency/* /home/app/libs/
...
ENTRYPOINT ["java", "-cp", "/home/app/libs/*:/home/app/classes/", "com.example.app.Application"]Building GraalVM-based Docker images
$ mvn package -Dpackaging=docker-nativeIf the <packaging> is set to docker-native, this plugin will use a Docker client to build and tag custom Docker
images. In this case, the micronaut.runtime property will also determine how the image is prepared.
For Micronaut-managed docker-native builds and generated Dockerfiles, the plugin adds -H:+SharedArenaSupport to
the native-image arguments by default when the selected builder is known to be a GraalVM/Java 25 or newer native-image
builder. Current Netty native images require this flag on those builders. The plugin skips the default for older
builders and for custom builder images whose GraalVM major version cannot be confidently detected; when you know a
custom builder supports the option, add it explicitly with nativeImageBuildArgs or micronaut.native-image.args.
-
Default runtime.
-
Default image (pinned immutable base):
mvn package -Dpackaging=docker-native. -
JDK HTTP server runtime (Starter compatibility alias for the default runtime; same behavior as the default image):
mvn package -Dpackaging=docker-native -Dmicronaut.runtime=http_server_jdk. -
Static image:
mvn package -Dpackaging=docker-native -Dmicronaut.native-image.static=true. This uses GraalVM’s--static --libc=muslflags and then puts the binary in ascratchimage. -
Mostly static image:
mvn package -Dpackaging=docker-native -Dmicronaut.native-image.base-image-run=gcr.io/distroless/cc-debian12 -Pgraalvm. This will create a "mostly" static native image and adds automatically-H:+StaticExecutableWithDynamicLibCflag. -
Custom runtime image:
mvn package -Dpackaging=docker-native -Dmicronaut.native-image.base-image-run=your-own-image-for-run-the-native-image
-
-
Oracle Cloud Function:
mvn package -Dpackaging=docker-native -Dmicronaut.runtime=oracle_function. -
AWS Lambda (custom runtime):
mvn package -Dpackaging=docker-native -Dmicronaut.runtime=lambda.
For builds behind an HTTP or HTTPS proxy, docker-native automatically forwards the standard JVM proxy
properties as Docker build arguments. The plugin maps http.proxyHost, http.proxyPort, https.proxyHost,
https.proxyPort, and http.nonProxyHosts to the corresponding HTTP_PROXY, HTTPS_PROXY, and NO_PROXY
build args, including their lowercase variants.
$ mvn package -Dpackaging=docker-native \
-Dhttp.proxyHost=proxy.example.com \
-Dhttp.proxyPort=8080 \
-Dhttps.proxyHost=proxy.example.com \
-Dhttps.proxyPort=8080 \
'-Dhttp.nonProxyHosts=localhost|127.0.0.1|*.example.com'Prefer passing credential-bearing proxy values from the command line or CI secrets rather than committing them to the project POM.
Bringing your own native Dockerfile
$ mvn package -Dpackaging=docker-nativeIf there is a Dockerfile in the project’s root directory and the selected docker-native path produces a Docker
container image, the file will be copied into target/ and used to build that image with target/ as the Docker
build context.
AWS Lambda and other docker-native modes that only produce ZIP artifacts such as function.zip do not consult the
project-root Dockerfile and continue to use the plugin’s bundled native Dockerfiles for the native-image build step.
For image-building docker-native modes, the plugin still prepares the native-image inputs under target/ and passes
the same build arguments as the bundled native Dockerfiles where applicable. Depending on the runtime and image mode,
it may provide:
-
BASE_IMAGE -
BASE_IMAGE_RUNwhenmicronaut.native-image.staticis nottrue -
CLASS_NAMEwhen the runtime still needs an application entrypoint -
PORTS
For example, Oracle Cloud Function images disable CLASS_NAME, and static native images do not pass BASE_IMAGE_RUN.
If your custom Dockerfile needs those values, declare the matching ARG instructions only for the arguments used by
your build and copy the generated native build inputs from the target/ context. For example:
ARG BASE_IMAGE
ARG BASE_IMAGE_RUN
FROM ${BASE_IMAGE} AS builder
WORKDIR /home/app
COPY classes /home/app/classes
COPY dependency/* /home/app/libs/
COPY graalvm-reachability-metadata /home/app/graalvm-reachability-metadata
COPY native/generated /home/app/
COPY *.args /home/app/graalvm-native-image.args
ARG CLASS_NAME
RUN native-image @/home/app/graalvm-native-image.args -H:Class=${CLASS_NAME} -H:Name=application -cp "/home/app/libs/*:/home/app/classes/"
FROM ${BASE_IMAGE_RUN}
COPY --from=builder /home/app/application /app/application
ARG PORTS=8080
EXPOSE ${PORTS}
ENTRYPOINT ["/app/application"]The image built can be customised using Jib. In particular, you can set:
-
The builder image, using
<from><image>. If the builder image comes from a registry that requires authentication, you can use<from><auth><username>and<from><auth><password>. Check the Jib documentation for more details. -
The image name/tags that will be used for building, using either
<to><image>and/or<to><tags>.
You can also override the native build-stage image with the Micronaut-specific micronaut.native-image.base-image
property. This is the preferred override when you want to stay within Micronaut Maven Plugin configuration instead of
using Jib-specific <from><image> or jib.from.image.
$ mvn package -Dpackaging=docker-native \
-Dmicronaut.native-image.base-image=container-registry.oracle.com/graalvm/native-image:21-ol8Use micronaut.native-image.base-image for the native builder stage and micronaut.native-image.base-image-run for
the final runtime image. The native builder-stage image is resolved in this order:
-
jib.from.image. -
micronaut.native-image.base-image. -
Jib
<from><image>. -
The plugin-computed default Oracle GraalVM GFTC builder image.
That keeps jib.from.image as the highest-precedence override so existing automation keeps working unchanged, while
still letting Micronaut-specific configuration win over the Jib POM builder image.
You can also use some system properties from the command line:
-
jib.from.image. -
jib.from.auth.username. -
jib.from.auth.password. -
jib.to.image. -
jib.to.tags. -
jib.to.auth.username. -
jib.to.auth.password. -
jib.to.credHelper.
When using jib.buildGoal=build, set jib.to.image to the registry image to publish. Credentials can come from
Jib-supported configuration such as jib.to.auth.*, jib.to.credHelper, Maven settings, environment-backed POM
properties, or standard registry credential helpers. jib.buildGoal=buildTar only creates target/jib-image.tar; it
does not publish to a registry and is not a deploy mode.
Note that changing the builder image to a totally different one than the default might break image building, since the rest
of the build steps expect a certain builder-stage base image. By default, that builder-stage base image comes from
container-registry.oracle.com/graalvm/native-image.
If you need a stricter reproducibility guarantee than a moving image tag provides, override the builder-stage image with a
digest-pinned reference via micronaut.native-image.base-image or jib.from.image.
If the selected builder image requires authentication, continue using Jib auth configuration such as
jib.from.auth.username and jib.from.auth.password.
In the case of AWS custom runtime, it starts from amazonlinux:2023, and this cannot be changed. Also, in this case the
result is not a tagged Docker image, but a function.zip archive that contains the bootstrap launch script and the native binary.
Essentially, what you need to upload to AWS Lambda. Also in this case, the Micronaut Maven Plugin will detect the host
operating system architecture (based on the os.arch Java system property) and will install the corresponding GraalVM
binary distribution inside the Docker image. This means that when running packaging from an X86_64 (Intel/AMD) machine,
the produced native image will be an amd64 binary, whilst on an ARM host (such as the new Mac M1) it will be an
aarch64 binary.
For AWS Lambda custom runtimes, use lambdaBootstrapArguments to append extra native bootstrap flags after the plugin’s
default flags. This is different from appArguments, which apply to the Oracle Cloud Function Dockerfile path.
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<configuration>
<lambdaBootstrapArguments>
<arg>-Dio.netty.noUnsafe=true</arg>
<arg>-Dio.netty.noPreferDirect=false</arg>
</lambdaBootstrapArguments>
</configuration>
</plugin>Or from the command line:
$ mvn package -Dpackaging=docker-native -Dmicronaut.runtime=lambda \
-Dmicronaut.lambda.bootstrap.args="-Dio.netty.noUnsafe=true,-Dio.netty.noPreferDirect=false"Also, to pass additional arguments to the native-image process:
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<configuration>
<nativeImageBuildArgs>
<nativeImageBuildArg>--verbose</nativeImageBuildArg>
</nativeImageBuildArgs>
</configuration>
</plugin>Or from the command line:
$ mvn package -Dpackaging=docker-native -Dmicronaut.native-image.args="--verbose"Building CRaC-based Docker images
Warning: The Micronaut CRaC module is in experimental stages. Use at your own risk!
The CRaC (Coordinated Restore at Checkpoint) Project researches coordination of Java programs with mechanisms to checkpoint (make an image of, snapshot) a Java instance while it is executing. Restoring from the image could be a solution to some problems with the start-up and warm-up times.
Creation of a pre-warmed, checkpointed docker image can be done with the following command:
$ mvn package -Dpackaging=docker-cracThis will first create an intermediate image that contains the application and all of its dependencies.
This image is then executed and warmed up via a warmup.sh command, and a checkpoint is taken.
A final image is then built which contains this checkpoint.
You will then be able to run your image via:
docker run --cap-add=cap_sys_ptrace -p 8080:8080 <image-name>The image built can be customised using Jib. In particular, you can set:
-
The base image, using
<from><image>. -
The image name/tags that will be used for building, using either
<to><image>and/or<to><tags>.
Checking an application is ready
As part of the checkpointing process, the application will be tested until it is ready to receive requests.
This is by default done by executing the command curl --output /dev/null --silent --head http://localhost:8080, however you can override this by setting the crac.readiness property in your build.
<properties>
<crac.readiness>curl --output /dev/null --silent --head https://localhost</crac.readiness>
</properties>Customizing warmup
The default warmup script simply makes a request to port 8080 of the application.
However, you can specify your own by placing a Bash script named warmup.sh in the root project folder.
For example, to hit the root endpoint 10 times, you could create a file with the following contents:
#!/bin/bash
for run in {1..10}; do
curl --output /dev/null --silent http://localhost:8080
doneCustomizing the JDK
By default, the CRaC JDK used to build the image will be for the current system architecture and Java 25. These can be overridden by passing properties to the build:
<properties>
<crac.java.version>25</crac.java.version>
<crac.arch>amd64</crac.arch>
<crac.os>linux-glibc</crac.os>
</properties>|
Note
|
Currently only Java 25, and amd64 and aarch64 architectures are supported.
|
2.3 Generating Dockerfiles
Maven generates this reference from the plugin's goal descriptors when it builds the plugin site. Read Generating Dockerfiles on the published Micronaut Maven Plugin site.
Similarly to the packaging support, with this plugin you can use mvn deploy as the only command
required to deploy an application that, depending on the <packaging>:
-
jar(default): will deploy the artifact to a remote repository usingorg.apache.maven.plugins:maven-deploy-plugin:deploy. -
dockerordocker-native: will push the Docker image to the configured Docker registry. -
native-imagewithmicronaut.native-image.jib.enabled=true: writes a daemonless tarball duringpackageby default, or publishes duringpackagewhen-Djib.buildGoal=buildis set. -
k8soropenshift: will delegate image publication to Eclipse JKube’spushgoal for the selected platform.
You can use Jib to configure which registry should the image be pushed to. Refer to the Jib Maven Plugin documentation to see what are the configuration options that can be used.
For example, to push an image to Docker Hub:
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<configuration>
<to>
<image>my-company/my-app:${project.version}</image>
</to>
</configuration>
</plugin>Then, you can execute mvn deploy -Dpackaging=docker or mvn deploy -Dpackaging=docker-native.
For JVM docker packaging, the jib.buildGoal value determines how the image is published:
jib.buildGoal |
Deploy behavior |
|---|---|
Omitted or |
Jib builds the image into the local Docker daemon during |
|
Jib publishes the image directly to the registry during |
|
Unsupported for |
Use build for daemonless deploy from CI environments that do not have a local Docker daemon:
mvn deploy -Dpackaging=docker \
-Djib.buildGoal=build \
-Djib.to.image=registry.example.com/team/my-app:1.0.0The command must include jib.to.image or equivalent Jib <to><image>…</image></to> configuration. Configure
registry credentials with Jib-supported mechanisms such as Maven settings, jib.to.credHelper, environment-backed
jib.to.auth.username and jib.to.auth.password properties, or standard registry credential helpers. Do not commit
plain-text registry secrets to the POM.
For daemonless native executable images, use native-image, enable the native image Jib workflow, and set Jib’s registry
build goal:
mvn package -Dpackaging=native-image \
-Dmicronaut.native-image.jib.enabled=true \
-Djib.buildGoal=build \
-Djib.to.image=my-company/my-app:latestThis path builds the local native executable, copies only that executable into a container image, and pushes with Jib registry
credentials. mvn deploy -Dpackaging=native-image also runs the package phase, so the same Jib registry publish path
is used when jib.buildGoal=build is configured.
For JKube-backed deployments, declare the matching JKube plugin in your POM and run either:
$ mvn deploy -Dpackaging=k8s
$ mvn deploy -Dpackaging=openshiftk8s maps deploy to org.eclipse.jkube:kubernetes-maven-plugin:push, while openshift maps deploy to
org.eclipse.jkube:openshift-maven-plugin:push.
For native image Jib image creation, omitting jib.buildGoal produces target/jib-image.tar by default, and
-Djib.buildGoal=build publishes directly to jib.to.image during package.
You can also omit the plugin declaration in your POM, and execute directly:
$ mvn deploy -Dpackaging=docker-native -Djib.to.image=my-company/my-app:latestNote that in Maven, the deploy phase runs after the package phase (among others), so invoking deploy will also build
the Docker image. Check the packaging support to see what options can be used.
This plugin will use your Docker configuration at ~/.docker/config.json. Essentially, if you can run docker push from
your command line, you will also be able to mvn deploy your application.
In addition to that, you can supply credentials via username and password:
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<configuration>
<to>
<image>gcr.io/my-gcp-project/my-app</image>
<auth>
<username>${env.REGISTRY_USERNAME}</username>
<password>${env.REGISTRY_PASSWORD}</password>
</auth>
</to>
</configuration>
</plugin>Or with the command line:
$ mvn deploy -Dpackaging=docker-native -Djib.to.image=gcr.io/my-gcp-project/my-app -Djib.to.auth.username=$REGISTRY_USERNAME -Djib.to.auth.password=$REGISTRY_PASSWORDWARNING: The Micronaut AOT module is in experimental stages. Use at your own risk!
Micronaut AOT is a module which aims at pre-computing a number of things at build time in order to provide faster startup times and smaller binaries. At the moment, it supports optimizing Micronaut applications only (Micronaut libraries or functions will be supported in a future release).
To enable Micronaut AOT, simply set the property micronaut.aot.enabled, either in the POM or via the command-line:
$ mvn package -Dmicronaut.aot.enabled=trueThat integrated path continues to work through micronaut-maven-plugin on 5.0.x, including the existing packaging and
mn:run flows.
Standalone AOT plugin
If a module only needs Micronaut AOT support, it can use the standalone micronaut-maven-aot-plugin without applying
the main Micronaut Maven plugin:
<build>
<plugins>
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-aot-plugin</artifactId>
<version>{site-version}</version>
<executions>
<execution>
<goals>
<goal>aot-analysis</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>The standalone plugin keeps the same goals, but it uses the mn-aot prefix for direct invocation:
$ mvn mn-aot:aot-sample-config -Dmicronaut.aot.enabled=trueWhen both plugins are declared in the same build, micronaut-maven-plugin remains the owner of integrated AOT
execution and the standalone aot-analysis goal will skip itself to avoid double-running AOT.
When Micronaut AOT is enabled, the packaged (or exploded) format of the application will contain some optimizations computed at build time. It may contain, for example, additional classes, or even have different resources.
IMPORTANT: Micronaut AOT is a deployment optimization: it adds to build time, in order to make the final application faster to start, or the native images smaller. Therefore, if you use the AOT tasks during development, your feedback cycle will be slower (but the application will start faster). It is a good idea, however, to check the result of the optimization locally, similarly to what you’d do for a native image.
Currently, Micronaut AOT supports 2 runtimes: jit (the default) and native. To change it, use the
micronaut.aot.runtime property. Note that if your packaging and micronaut.aot.runtime properties don’t match,
the plugin will issue a warning in the build log:
$ mvn package -Dmicronaut.aot.enabled=true -Dpackaging=native-image
[INFO] --- mn:4.0.0:aot-sample-config (default-cli) @ demo ---
[WARNING] Packaging is set to [native-image], but Micronaut AOT runtime is set to [jit]. Please change them so that they matchDefining additional AOT dependencies
It is possible to add additional dependencies to the AOT execution classpath that may be required by some optimizations,
or to include an external AOT optimizer (in the future, some modules such as micronaut-security may offer additional
optimizers that can be used).
For example, the logback.xml.to.java optimization requires additional dependencies that can be defined in your POM
as follows:
<build>
<plugins>
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<configuration>
<aotDependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>2.4.0</version>
</dependency>
</aotDependencies>
</configuration>
</plugin>
</plugins>
</build>Configuration
Micronaut AOT can be configured with a .properties file. To get started with the possible options and their
description, run the aot-sample-config goal:
$ mvn -Dmicronaut.aot.enabled mn:aot-sample-config
[INFO] ...
[INFO] Executing Micronaut AOT analysis
[INFO] Sample configuration file written to /my-app/target/aot/jit/aot.properties
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------Then, copy the target/aot/jit/aot.properties to your root directory, and adapt it to your needs. If using a different
directory, use the micronaut.aot.config property to specify its location.
For a full list of configuration options, check the aot-analysis goal documentation.
Excluding dependencies
If you want to exclude a dependency from AOT processing, use the aotExclusions configuration property.
For example, to exclude com.example:example use the following configuration:
<build>
<plugins>
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<configuration>
<aotExclusions>
<exclusion>
<groupId>com.example</groupId>
<artifactId>example</artifactId>
</exclusion>
</aotExclusions>
</configuration>
</plugin>
</plugins>
</build>|
Note
|
It is recommended to add AOT exclusions if you are building native image and have
exclusions in the native-maven-plugin.
|
Micronaut Test Resources adds support for managing external resources which are required during development or testing. In particular, it integrates with Testcontainers to provide throwaway containers for resources like databases or other external services like Kafka or RabbitMQ.
Test resources are handled by a "test resources service", which is a server that accepts requests for test resources. The Maven plugin manages the service lifecycle. A test resources request is, to simplify, a request to resolve a missing configuration property. For example, if the kafka.bootstrap-servers property isn’t set, Micronaut will query the test resources service for the value of this property. This will trigger the creation of a Kafka test container, and the service will answer with the URI to the bootstrap server.
You can enable test resources support simply by setting the property micronaut.test.resources.enabled (either in your
POM or via the command-line).
This will be sufficient for most use cases, and Micronaut will automatically start containers, for example, when a
particular property is not present in your configuration and that you run tests (mvn test) or the application in
development mode (mvn mn:run).
For example, if the datasources.default.url configuration property is missing, and that your configuration contains:
datasources:
default:
dialect: MYSQLThen a MySQL database will automatically be started and available for use in your tests: the url, username and password configuration properties will automatically be injected to your application.
Please refer to the Micronaut Test Resources documentation for a list of all supported modules and their configuration options.
Standalone Test Resource Service
The default behaviour works particularly well in single-module projects, or in multi-module projects where test resources are not shared between modules. However, in some cases, you may want to reuse test containers for multiple projects of the same multi-project build, in order to save startup times for example.
For example, imagine a multi-project build which consists of :
-
A Kafka consumer.
-
A Kafka producer.
-
Functional tests integrating both.
If each project enables the Test Resources integration independently, then each project will use its own Test Resources server, separate from the others.
However, you might want to run the consumer in one terminal, and the producer in another, and still want them to talk to
the same Kafka cluster. For this you can use a shared test server, by passing the micronaut.test.resources.shared
system property, or setting <shared>true</shared> in the Micronaut Maven Plugin configuration.
Test Resource Service lifecycle
Test resources are handled by a service which is, by default, started at the beginning of a build, and stopped at the end.
For example, if you invoke:
$ mvn testThen the test resources service will be started before tests are executed, then tests will share the resources provided by the service. Any test resource started during the test will be stopped when the build finishes.
In development mode, the test resources service is also started in the same JVM. For example, if you run:
$ mvn mn:runThen the test resources will be spawned before the application starts, and shutdown when you Ctrl+C the mn:run
execution.
Keeping the Test Resources Service alive
If you want to start the test resources service in the background, and keep it alive for multiple, independent builds
(different invocations on the command line for example), you can run the mn:start-testresources-service goal:
$ mvn mn:start-testresources-service
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------------< com.example:demo >--------------------------
[INFO] Building demo 0.1
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- mn:4.0.0:start-testresources-service (default-cli) @ demo ---
[INFO] Server settings found in /private/tmp/demo/target/../.micronaut/test-resources
[INFO] Starting Micronaut Test Resources server
18:37:31.043 [ForkJoinPool.commonPool-worker-13] INFO i.m.t.e.TestResourcesResolverLoader - Loaded 2 test resources resolvers: io.micronaut.testresources.mysql.MySQLTestResourceProvider, io.micronaut.testresources.testcontainers.GenericTestContainerProvider
18:37:31.290 [main] INFO i.m.testresources.server.Application - A Micronaut Test Resources server is listening on port 51082, started in 387ms
[INFO] Micronaut Test Resources service is started in the background. To stop it, run the following command: 'mvn mn:stop-testresources-service'
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.813 s
[INFO] Finished at: 2022-07-08T18:37:31+02:00
[INFO] ------------------------------------------------------------------------To stop it, use the mn:stop-testresources-service goal.
Adding modules or libraries to the Test Resources service classpath
If not using classpath inference, or when the inference doesn’t produce the desired result, you can add dependencies
to the Test Resources service classpath with a <testResourcesDependencies> block.
For example, if the classpath inference mechanism fails to detect that you need a MySQL test container, you can configure it like this:
<build>
<plugins>
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<configuration>
<classpathInference>false</classpathInference>
<testResourcesDependencies>
<dependency>
<groupId>io.micronaut.testresources</groupId>
<artifactId>micronaut-test-resources-jdbc-mysql</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
</testResourcesDependencies>
</configuration>
</plugin>
</plugins>
</build>The versions of those dependencies will be resolved against the Micronaut BOM.
Using a sibling reactor module for custom resolvers
If you want to implement a custom TestResourcesResolver in the same multi-module Maven build as the application which
uses it, put the resolver in a dedicated sibling module and add that module to <testResourcesDependencies> in the
consumer module.
This is the Maven-native equivalent of Gradle’s src/testResources/** convenience source set: the resolver stays in a
normal Java module, participates in the same reactor build, and is added explicitly to the Test Resources service
classpath.
The dedicated resolver module should include:
-
The custom
TestResourcesResolverimplementation. -
A
META-INF/services/io.micronaut.testresources.core.TestResourcesResolverfile listing the implementation class. -
A dependency on
micronaut-test-resources-core.
For example, the parent POM can define separate resolver and app modules:
<modules>
<module>resolver</module>
<module>app</module>
</modules>The resolver module can package the implementation and service loader metadata as a normal JAR:
<project>
<parent>
<groupId>io.micronaut.build.examples</groupId>
<artifactId>test-resources-custom-reactor-dependency-parent</artifactId>
<version>0.1</version>
</parent>
<artifactId>custom-reactor-resolver</artifactId>
<dependencies>
<dependency>
<groupId>io.micronaut.testresources</groupId>
<artifactId>micronaut-test-resources-core</artifactId>
</dependency>
</dependencies>
</project>Then the consuming module can expose that sibling artifact to the Test Resources service:
<build>
<plugins>
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<configuration>
<testResourcesDependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>custom-reactor-resolver</artifactId>
<version>${project.version}</version>
</dependency>
</testResourcesDependencies>
</configuration>
</plugin>
</plugins>
</build>When you run mvn test or mvn verify from the parent project, Maven builds the sibling resolver module in the same
reactor and the plugin adds that artifact to the Test Resources service classpath for the consuming module.
The list of supported modules is described in the Micronaut Test Resources documentation.
Additional configuration options
You can see all the additional configuration options in the
start-testresources-service goal documentation.
This plugin integrates with Micronaut OpenAPI to provide support for generating OpenAPI clients or servers.
The plugin adds a couple goals which can be used to generate code:
-
the mn:generate-openapi-client goal can be used to generate a client from an OpenAPI definition
-
the mn:generate-openapi-server goal can be used to generate a server skeleton from an OpenAPI definition
In both cases, the code is generated in your target directory and integrated into the build lifecycle.
In particular, in case you are generating a server, the generated code will be interfaces that you will have to implement in your main sources.
Generating a client
In order to generate a client, the minimal thing to do is to configure a couple properties:
<properties>
...
<micronaut.openapi.generate.client>true</micronaut.openapi.generate.client>
<micronaut.openapi.definition>src/openapi/petstore.json</micronaut.openapi.definition>
</properties>It is however recommended to define the packages which will be used for code generation:
<properties>
...
<micronaut.openapi.generate.client>true</micronaut.openapi.generate.client>
<micronaut.openapi.definition>src/openapi/petstore.json</micronaut.openapi.definition>
<micronaut.openapi.invoker.package.name>com.mycompany.invoker</micronaut.openapi.invoker.package.name>
<micronaut.openapi.api.package.name>com.mycompany.api</micronaut.openapi.api.package.name>
<micronaut.openapi.model.package.name>com.mycompany.api</micronaut.openapi.model.package.name>
</properties>The full list of configuration properties can be found here.
Generating a server
Generating a server can be done in a similar way to generating a client, except that the code which is generated for the server (not the model) is simply interfaces that you will have to implement:
<properties>
...
<micronaut.openapi.generate.server>true</micronaut.openapi.generate.server>
<micronaut.openapi.definition>src/openapi/petstore.json</micronaut.openapi.definition>
</properties>We also recommended to define the packages which will be used for code generation:
<properties>
...
<micronaut.openapi.generate.server>true</micronaut.openapi.generate.server>
<micronaut.openapi.definition>src/openapi/petstore.json</micronaut.openapi.definition>
<micronaut.openapi.controller.package.name>com.mycompany.controller</micronaut.openapi.controller.package.name>
<micronaut.openapi.invoker.package.name>com.mycompany.invoker</micronaut.openapi.invoker.package.name>
<micronaut.openapi.api.package.name>com.mycompany.api</micronaut.openapi.api.package.name>
<micronaut.openapi.model.package.name>com.mycompany.api</micronaut.openapi.model.package.name>
</properties>The full list of configuration properties can be found here.
When project dependencies contain beans but don’t contain the Micronaut bean definitions the @Import annotation can
be used to import those beans and allow them to be injected in the Micronaut application context. Since this annotation
is handled by an annotation processor which can’t list the available packages each package must be defined in the
@Import annotation which can be cumbersome.
This plugin is able to generate a Micronaut bean factory which imports the beans from the dependencies. The list of packages from which the beans are imported can be controlled by filtering the dependencies and the packages using regular expressions.
In order to import beans from the dependencies the minimal thing to do is to enable the import factory:
<properties>
...
<micronaut.importfactory.enabled>true</micronaut.importfactory.enabled>
</properties>It is however recommended to define a filter for the dependencies and for the packages:
<properties>
...
<micronaut.importfactory.enabled>true</micronaut.importfactory.enabled>
<micronaut.importfactory.includeDependenciesFilter>my.company:.*</micronaut.importfactory.includeDependenciesFilter>
<micronaut.importfactory.excludeDependenciesFilter>my.company:exclude-this.*</micronaut.importfactory.excludeDependenciesFilter>
<micronaut.importfactory.includePackagesFilter>my.company.library.*</micronaut.importfactory.includePackagesFilter>
<micronaut.importfactory.excludePackagesFilter>my.company.library.internal.*</micronaut.importfactory.excludePackagesFilter>
<micronaut.importfactory.targetPackage>my.company.application</micronaut.importfactory.targetPackage>
</properties>The full list of configuration properties can be found here.
This plugin integrates with Micronaut JSON Schema to provide support for generating beans from JSON Schema.
The mn:generate-jsonschema goal is integrated into the generate-sources lifecycle phase and, if enabled, will generate sources in the target directory.
In order to generate Java Beans, the minimal thing to do is enable the goal and specify an input source.
<properties>
...
<micronaut.jsonschema.generator.enabled>true</micronaut.jsonschema.generator.enabled>
<micronaut.jsonschema.generator.input-file>src/main/resources/animal.schema.json</micronaut.jsonschema.generator.input-file>
</properties>Some important notes on configuration settings:
-
The default generation language is
JAVA, but it can be changed. Only languages supported by Micronaut SourceGen are supported. -
The available input values are
input-url,input-file, andinput-directory. At least one type of input values needs to be provided. If more than one input value is given, only the first non-null value will be used in the aforementioned order. -
The generator supports all remote references that obey at least one of the pattern rules given in
accepted-url-patternsparameter. This parameter is configurable, and it’s default value is["^https://./..json"].
The full list of configuration properties can be found in the goal documentation.
The Micronaut Maven Plugin can validate your application’s configuration files (for example application.yml) using JSON Schema.
The build fails when validation reports errors.
Validation is disabled by default and must be explicitly enabled.
Goals
-
mn:validate-dev-configuration-
Validates using the
devenvironment. -
This goal is invoked by
mn:runand runs validation only when explicitly enabled.
-
-
mn:validate-configuration-
Intended for
mvn package(for example production configuration). -
Default environments: none.
-
-
mn:validate-test-configuration-
Intended for
mvn test. -
Default environments:
test.
-
Binding to the lifecycle
Configuration validation goals are wired when using Micronaut packaging types (jar, native-image, docker, docker-native, docker-crac, k8s, openshift), but validation only executes when explicitly enabled:
-
validate-configurationruns during theprepare-packagephase (beforemvn package) -
validate-test-configurationruns during thetestphase (as part ofmvn test) -
validate-dev-configurationis invoked bymn:run
If you are not using Micronaut packaging or want to customize the phase bindings, you can configure explicit executions:
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<version>${micronaut-maven-plugin.version}</version>
<executions>
<execution>
<id>validate-config</id>
<goals>
<goal>validate-configuration</goal>
</goals>
<phase>prepare-package</phase> <!-- optional: customize phase -->
</execution>
<execution>
<id>validate-test-config</id>
<goals>
<goal>validate-test-configuration</goal>
</goals>
<phase>test</phase> <!-- optional: customize phase -->
</execution>
</executions>
</plugin>Configuration
The mojos share a configurationValidation block and expose options equivalent to the validator CLI.
<plugin>
<groupId>io.micronaut.maven</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<configuration>
<configurationValidation>
<enabled>true</enabled>
<!-- CLI options -->
<suppressions>
<suppression>.*\.password</suppression>
</suppressions>
<suppressInjectErrors>
<suppressInjectError>com.example.internal.*</suppressInjectError>
</suppressInjectErrors>
<failOnNotPresent>true</failOnNotPresent>
<deduceEnvironments>false</deduceEnvironments>
<validateDependencyInjection>false</validateDependencyInjection>
<format>both</format> <!-- json|html|both -->
<outputDirectory>${project.build.directory}/micronaut/config-validation</outputDirectory>
<!-- Per-scenario overrides -->
<dev>
<environments>
<environment>dev</environment>
</environments>
</dev>
<packageValidation>
<environments>
<environment>prod</environment>
</environments>
</packageValidation>
<test>
<!-- additional environments are appended; 'test' environment is included by default when validation runs -->
<environments>
<environment>ci</environment>
</environments>
</test>
</configurationValidation>
</configuration>
</plugin>If <enabled> is not set (or is set to false), validation does not run; set it to true to enable validation.
Classpath configuration
Each scenario can be configured independently via:
-
classpathElements: replaces the default classpath used by the validator -
additionalClasspathElements: entries appended to the default classpath
Dependency injection validation
By default, configuration validation checks configuration keys and values only. You can also validate Micronaut dependency injection wiring (missing beans, unsatisfied injections, etc.) by enabling:
<configurationValidation>
<enabled>true</enabled>
<validateDependencyInjection>true</validateDependencyInjection>
</configurationValidation>When enabled, dependency-injection issues are included in the generated reports and cause the build to fail.
If you need to suppress known dependency-injection issues (for example optional integrations in test fixtures), use
suppressInjectErrors:
<configurationValidation>
<enabled>true</enabled>
<validateDependencyInjection>true</validateDependencyInjection>
<suppressInjectErrors>
<suppressInjectError>com.example.optional.MissingBean</suppressInjectError>
<suppressInjectError>com.example.experimental.*</suppressInjectError>
</suppressInjectErrors>
</configurationValidation>suppressInjectError supports exact class names and * wildcard patterns.
Reports
Reports are written under ${project.build.directory}/micronaut/config-validation/<scenario> by default.
Depending on format, the plugin generates:
-
configuration-errors.json -
configuration-errors.html
Caching
Validation results are cached on disk to avoid re-running on every build.
By default, validation re-runs when src/main/resources changes.
When validateDependencyInjection is enabled, classpath entry metadata/content is also fingerprinted for cache invalidation.
Disable caching with:
<configurationValidation>
<enabled>true</enabled>
<cacheEnabled>false</cacheEnabled>
</configurationValidation>