Java run plugin maven

Maven Tutorial — Maven Run Java Main

After packaging the source to a Jar file we can use the following three ways to run the Java main method.

We can use Maven exec plugin to run the main method of a Java class, with the project dependencies automatically included in the classpath.

Running from Command line

Suppose we have the project created in the previous chapters. To run the Java main method from Maven, we can use the following command.

mvn exec:java -Dexec.mainClass="com.java2s.ide.App" 

The code above generates the following result.

c:\mvn_test\xmlFileEditor>mvn exec:java -Dexec.mainClass="com.java2s.ide.App" [INFO] Scanning for projects. Downloading: https://repo.maven.apache.org/maven2/org/codehaus/mojo/exec-maven-plugin/maven-metadata.xml . [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building xmlFileEditor 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- exec-maven-plugin:1.3.2:java (default-cli) @ xmlFileEditor --- Downloading: https://repo.maven.apache.org/maven2/junit/junit/4.11/junit-4.11.pom . [WARNING] Warning: killAfter is now deprecated. Do you need it ? Please comment on MEXEC-6. Hello World! [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 8.847 s [INFO] Finished at: 2014-11-03T16:25:54-08:00 [INFO] Final Memory: 22M/369M [INFO] ------------------------------------------------------------------------ c:\mvn_test\xmlFileEditor>
mvn exec:java -Dexec.mainClass="com.java2s.ide.App" -Dexec.args="arg0 arg1 arg2" 

With runtime dependencies in the CLASSPATH:

mvn exec:java -Dexec.mainClass="com.java2s.ide.App" -Dexec.classpathScope=runtime

Running in a phase in pom.xml

We can run the main method in a maven phase. For example, you can run the App.main() method as part of the test phase.

   org.codehaus.mojo exec-maven-plugin 1.1.1  test java  com.java2s.ide.App arg0 arg1        

To run the exec plugin with above configuration, simply run the corresponding phase.

Читайте также:  Формальные параметры функции питон

Running in a profile in pom.xml

We can run the main method in a different profile. wrap the above config in the tag.

  code-generator   org.codehaus.mojo exec-maven-plugin 1.1.1  test java  com.java2s.ide.App arg0 arg1          

To call the above profile, run the following command:

java2s.com | © Demo Source and Support. All rights reserved.

Источник

Guide to Developing Java Plugins

This guide is intended to assist users in developing Java plugins for Maven.

Important Notice

You will typically name your plugin -maven-plugin .

Calling it maven—plugin (note «Maven» is at the beginning of the plugin name) is strongly discouraged since it’s a reserved naming pattern for official Apache Maven plugins maintained by the Apache Maven team with groupId org.apache.maven.plugins .

Using this naming pattern is an infringement of the Apache Maven Trademark.

Your First Plugin

In this section we will build a simple plugin with one goal which takes no parameters and simply displays a message on the screen when run. Along the way, we will cover the basics of setting up a project to create a plugin, the minimal contents of a Java mojo which will define goal code, and a couple ways to execute the mojo.

Your First Mojo

At its simplest, a Java mojo consists simply of a single class representing one plugin’s goal. There is no requirement for multiple classes like EJBs, although a plugin which contains a number of similar mojos is likely to use an abstract superclass for the mojos to consolidate code common to all mojos.

When processing the source tree to find mojos, plugin-tools looks for classes with @Mojo Java 5 annotation. Any class with this annotation are included in the plugin configuration file.

A Simple Mojo

Listed below is a simple mojo class which has no parameters. This is about as simple as a mojo can be. After the listing is a description of the various parts of the source.

package sample.plugin; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; /** * Says "Hi" to the user. * */ @Mojo(name = "sayhi") public class GreetingMojo extends AbstractMojo < public void execute() throws MojoExecutionException < getLog().info("Hello, world."); >>
  • The class org.apache.maven.plugin.AbstractMojo provides most of the infrastructure required to implement a mojo except for the execute method.
  • The annotation » @Mojo » is required and control how and when the mojo is executed.
  • The execute method can throw org.apache.maven.plugin.MojoExecutionException if an problem occurs. Throwing this exception causes a BUILD FAILURE message to be displayed.
  • The getLog method (defined in AbstractMojo ) returns a log4j-like logger object which allows plugins to create messages at levels of «debug», «info», «warn», and «error». This logger is the accepted means to display information to the user. Please have a look at the section Retrieving the Mojo Logger for a hint on its proper usage.

All Mojo annotations are described by the Mojo API Specification.

Project Definition

Once the mojos have been written for the plugin, it is time to build the plugin. To do this properly, the project’s descriptor needs to have a number of settings set properly:

groupId This is the group ID for the plugin, and should match the common prefix to the packages used by the mojos
artifactId This is the name of the plugin
version This is the version of the plugin
packaging This must be set to » maven-plugin «
dependencies A dependency must be declared to the Maven Plugin Tools API to resolve » AbstractMojo » and related classes

Listed below is an illustration of the sample mojo project’s pom with the parameters set as described in the above table:

 4.0.0 sample.plugin hello-maven-plugin 1.0-SNAPSHOT maven-plugin Sample Parameter-less Maven Plugin 3.9.0   org.apache.maven maven-plugin-api 3.0 provided   org.apache.maven.plugin-tools maven-plugin-annotations $ provided     org.apache.maven.plugins maven-plugin-plugin $  help-mojo  helpmojo       

Building a Plugin

There are few plugins goals bound to the standard build lifecycle defined with the maven-plugin packaging:

compile Compiles the Java code for the plugin
process-classes Extracts data to build the plugin descriptor
test Runs the plugin’s unit tests
package Builds the plugin jar
install Installs the plugin jar in the local repository
deploy Deploys the plugin jar to the remote repository

Executing Your First Mojo

The most direct means of executing your new plugin is to specify the plugin goal directly on the command line. To do this, you need to configure the hello-maven-plugin plugin in you project:

 .    sample.plugin hello-maven-plugin 1.0-SNAPSHOT     . 

And, you need to specify a fully-qualified goal in the form of:

mvn groupId:artifactId:version:goal

For example, to run the simple mojo in the sample plugin, you would enter » mvn sample.plugin:hello-maven-plugin:1.0-SNAPSHOT:sayhi » on the command line.

Tips: version is not required to run a standalone goal.

Shortening the Command Line

There are several ways to reduce the amount of required typing:

  • If you need to run the latest version of a plugin installed in your local repository, you can omit its version number. So just use » mvn sample.plugin:hello-maven-plugin:sayhi » to run your plugin.
  • You can assign a shortened prefix to your plugin, such as mvn hello:sayhi . This is done automatically if you follow the convention of using $-maven-plugin (or maven-$-plugin if the plugin is part of the Apache Maven project). You may also assign one through additional configuration — for more information see Introduction to Plugin Prefix Mapping.
  • Finally, you can also add your plugin’s groupId to the list of groupIds searched by default. To do this, you need to add the following to your $/.m2/settings.xml file:

At this point, you can run the mojo with » mvn hello:sayhi «.

Attaching the Mojo to the Build Lifecycle

You can also configure your plugin to attach specific goals to a particular phase of the build lifecycle. Here is an example:

    sample.plugin hello-maven-plugin 1.0-SNAPSHOT     sample.plugin hello-maven-plugin  compile sayhi      

This causes the simple mojo to be executed whenever Java code is compiled. For more information on binding a mojo to phases in the lifecycle, please refer to the Build Lifecycle document.

Mojo archetype

To create a new plugin project, you could using the Mojo archetype with the following command line:

mvn archetype:generate \ -DgroupId=sample.plugin \ -DartifactId=hello-maven-plugin \ -DarchetypeGroupId=org.apache.maven.archetypes \ -DarchetypeArtifactId=maven-archetype-plugin

Parameters

It is unlikely that a mojo will be very useful without parameters. Parameters provide a few very important functions:

  • It provides hooks to allow the user to adjust the operation of the plugin to suit their needs.
  • It provides a means to easily extract the value of elements from the POM without the need to navigate the objects.

Defining Parameters Within a Mojo

Defining a parameter is as simple as creating an instance variable in the mojo and adding the proper annotations. Listed below is an example of a parameter for the simple mojo:

/** * The greeting to display. */ @Parameter(property = "sayhi.greeting", defaultValue = "Hello World!" ) private String greeting;

The portion before the annotations is the description of the parameter. The @Parameter annotation identifies the variable as a mojo parameter. The defaultValue parameter of the annotation defines the default value for the variable. This value can include expressions which reference the project, such as » $ » (more can be found in the «Parameter Expressions» document). The property parameter can be used to allow configuration of the mojo parameter from the command line by referencing a system property that the user sets via the -D option.

Configuring Parameters in a Project

Configuring the parameter values for a plugin is done in a Maven project within the pom.xml file as part of defining the plugin in the project. An example of configuring a plugin:

 sample.plugin hello-maven-plugin 1.0-SNAPSHOT Welcome  

In the configuration section, the element name (» greeting «) is the parameter name and the contents of the element (» Welcome «) is the value to be assigned to the parameter.

Note: More details can be found in the Guide to Configuring Plugins.

Using Setters

You are not restricted to using private field mapping which is good if you are trying to make you Mojos resuable outside the context of Maven. Using the example above we could define public setters methods that the configuration mapping mechanism can use. You can also add @Parameter annotation on setter method (from version 3.7.0 of `plugin-tools`)

So our Mojo would look like the following:

public class MyQueryMojo extends AbstractMojo < // provide name for non matching field and setter name @Parameter(name = "url", property = "url") private String _url; @Parameter(property = "timeout") private int timeout; private String option0; private String option1; public void setUrl(String url) < _url = url; >public void setTimeout(int timeout) < this.timeout = timeout; >@Parameter(property = "options") public void setOptions(String[] options) < // we can do something more with provided parameter this.option0 = options[0]; this.option1 = options[1]; >public void execute() throws MojoExecutionException < . >>

Note the specification of the property name for each parameter which tells Maven what setter and getter to use when the field’s name does not match the intended name of the parameter in the plugin configuration.

Resources

  1. Mojo Documentation: Mojo API, Mojo annotations
  2. Maven Plugin Testing Harness: Testing framework for your Mojos.
  3. Plexus: The IoC container used by Maven.
  4. Plexus Common Utilities: Set of utilities classes useful for Mojo development.
  5. Commons IO: Set of utilities classes useful for file/path handling.
  6. Common Bugs and Pitfalls: Overview of problematic coding patterns.

Источник

Оцените статью