The Maven’s exec plugin also makes a lot of use of the generated classpath.
Because the exec plugin allows to execute the project’s application as defined
by the POM, it’s not surprising that the required classpath is taken from Maven.
In the following, the exec
goal of the plugin is used. Even if the java
goal is sufficient to execute Java application, the exec
is sometimes
beneficial because of:
The exec plugin provides another way to display the Maven generated classpath:
$ mvn exec:exec -Dexec.executable=echo -Dexec.args="%classpath"
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< net.gunther.cli:json2yaml >----------------------
[INFO] Building json2yaml 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- exec-maven-plugin:3.0.0:exec (default-cli) @ json2yaml ---
/home/gunther/_work/java/json2yaml/target/classes:/home/gunther/.m2/repository/javax/json/javax.json-api/1.1/javax.json-api-1.1.jar:/home/gunther/.m2/repository/org/glassfish/javax.json/1.1/javax.json-1.1.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
...
In this case the echo
command is executed and displays the classpath passed
in as %classpath
placeholder. The exec plugin substitutes this placeholder
when starting the application.
Please note, that the classpath does not contain test dependencies, but only
reference artifacts actually required to execute the project’s application.
Another usage of the Maven generated classpath by exec plugin is to actually
execute Java applications, eg.:
$ echo '{ "f1": "v1", "f2": "v2" }' | mvn exec:exec -Dexec.executable=java -Dexec.args="-cp %classpath net.gunther.cli.json.PrettyPrinter"
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< net.gunther.cli:json2yaml >----------------------
[INFO] Building json2yaml 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- exec-maven-plugin:3.0.0:exec (default-cli) @ json2yaml ---
{
"f1": "v1",
"f2": "v2"
}
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
...
In this case the java
executable is started, which requires the classpath to
be given as -cp %classpath
option. The placeholder is again substituted by
references to the project’s dependencies.
The input string { "f1": "v1", "f2": "v2" }
is piped to the JSON
pretty-printer demo application using STDIN
, the application writes given
JSON in beautified format to STDOUT
.