I see you found the nashorn-maven-plugin
to run Javascript. But the ScriptEngine
JS implementation has since been removed from the JRE, so that plugin won't work from Java 15 onwards unless you find a way to add the JS engine back to your classpath.
There is currently a more generic official maven plugin available to run small scripts in a very similar way. The Apache Maven Scripting Plugin can execute scripts in any JSR223
compatible scripting language.
The plugin uses the same ScriptEngine mechanism, which relies on service discovery (loading a service provider interface). This means that it can use any compatible scripting language by placing a specific library on your classpath.
For more references on the library options you have, see the following questions:
These also include code on how to list the currently available scripting languages (which is just JS for Java versions 8 to 15 if you don't add additional libraries).
I have successfully used this plugin with the language of my choice on Maven 3 and Java 17. See the full example below.
I would advice to use the <scriptFile>
option if at all possible, so you don't have to maintain code in the pom file. But if you need to use any ${...}
variables you might not be able to use the file option. In that case you can use the <script>
option. If needed you can include the CDATA marker to keep the XML valid.
The plugin does expose the entire MavenProject
model and a logger, that should cover most needs. It gives access to all the project information, properties and the build environment. The following variables are bound by default for that purpose:
In my case i used Beanshell
, and the plugin setup looks like this:
<!-- Scripting Plugin: run ScriptEngine compatible scripts -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-scripting-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>run-script</id>
<phase>compile</phase>
<goals>
<goal>eval</goal>
</goals>
</execution>
</executions>
<configuration>
<engineName>beanshell</engineName>
<!-- <scriptFile>use this when possible; no code in the POM is preferred</scriptFile> -->
<script>
log.info("Hello from " + project.getArtifact());
</script>
</configuration>
<dependencies>
<!-- Script Engine: Beanshell -->
<dependency>
<groupId>org.apache-extras.beanshell</groupId>
<artifactId>bsh</artifactId>
<version>2.0b6</version>
</dependency>
</dependencies>
</plugin>
You can use any id
and phase
you like in the execution
element.
By changing the dependency
and engineName
you can use any other compatible scripting language.
This gives the following output in the maven build log:
[INFO] --- maven-scripting-plugin:3.0.0:eval (run-script) @ tests ---
[INFO] Hello from local:tests:jar:1.0