preface

In the daily development of Maven projects, we have few opportunities to develop our own Maven plug-ins, because maven plug-ins on the market can basically meet our daily development needs. There are also many plugins available for Maven. See the links below for details

Maven.apache.org/plugins/ind…

Today’s focus is on the process of developing a Maven plug-in

Maven plugin development

There are two types of Maven plug-in development: Java Doc and annotation-based

Java development of doc

This works directly with Maven’s built-in skeleton

Select Maven-archetype-mojo to generate a template. The template is as follows

/**
 * Goal which touches a timestamp file.
 *
 * @goal touch
 * 
 * @phase process-sources
 */
public class MyMojo
    extends AbstractMojo
{
    /**
     * Location of the file.
     * @parameter expression="${project.build.directory}"
     * @required* /
    private File outputDirectory;

    public void execute(a)
        throws MojoExecutionException
    {
        File f = outputDirectory;

        if ( !f.exists() )
        {
            f.mkdirs();
        }

        File touch = new File( f, "touch.txt" );

        FileWriter w = null;
        try
        {
            w = new FileWriter( touch );

            w.write( "touch.txt" );
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( "Error creating file " + touch, e );
        }
        finally
        {
            if( w ! =null )
            {
                try
                {
                    w.close();
                }
                catch ( IOException e )
                {
                    // ignore
                }
            }
        }
    }
}

Copy the code

This is bone-by-bone dumb-ass generation, if you’re interested in it, you can try it, but I won’t talk about it here.

Appendix: Common Doc explanations for Maven documentation development

Each moJO must use the @goal annotation to indicate its Goal name, otherwise maven will not be able to recognize the Goal. There are many other notes, including the following:

@goal: The only annotation that must be declared is the target name used when the user calls the plugin from the command line or configures the plugin in the POM. If you are running compiler:compile target, compiler is the plugin’s goalPrefix, compile is the target name

@Phase: This target is bound to a phase in the default declaration cycle by default, so there is no need to declare phase when configuring the use of the plug-in target, such as the test target of the Maven-Surefire-Plugin with the @Phase TES annotation

@ requiresDependencyResolution: before running mojo must resolve all specified range of dependence, Such as maven – surefire – plugin test target with requiresDependencyResolution test annotation, said before the test, all test range dependent must be resolved

RequiresProject <true/false>: Whether the target must be run in a Maven project (such as test plug-ins used to test other projects), the default is true. Most plug-in targets depend on a project to run, with the exception of the System target of Maven-help-Plugin, which displays information about system properties and environment variables without the actual project.

@requiresOnline <true/false>: Whether maven must be online. The default value is false

RequiresReport <true/false>: Whether the project report is required to have been generated. The default is false

Aggregator: When moJO is running on a multi-module project, this annotation indicates that the target will only be running on the top-level module.

RequiresDirectInvocation <true/false>: When true, this target can only be invoked directly from the command line. The default is false

@execute goal=””: Make Maven run another goal before running this goal. If this is the plugin target, call the target name directly, otherwise, use “Prefix :goal”

@execute Phase =””: Have Maven run a parallel lifecycle up to the specified phase before running the target. The plug-in target is not executed until phase execution is complete

@execute lifecycle=”” phase =”” : Have Maven run a custom lifecycle up to the specified phase before running the target.

Parameters: This element describes all the parameters of a Mojo. Name, type, Required, editable (whether can be set in PEM.xml), description, for example, @parameter can be used to mark a field of moJO as a configurable parameter, that is, a moJO parameter. Support for Boolean, int, float, String, Date, File, a Url array, Collection, map, Propertes

Configuration: Provides default values for all Mojo parameters

Note: the explanation from the blogger wave DJ 86 blog blog.csdn.net/bobozai86/a…

Annotations to develop

1. Introduction of POM.xml

<dependencies>
      <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-plugin-api</artifactId>
        <version>3.52.</version>
        <scope>provided</scope>
      </dependency>

      <dependency>
        <groupId>org.apache.maven.plugin-tools</groupId>
        <artifactId>maven-plugin-annotations</artifactId>
        <version>3.52.</version>
        <scope>provided</scope>
      </dependency>

  </dependencies>
Copy the code

Note: PoM packaging needs to be specified as Maven-plugin

2, write a plug-in class inheritance org. Apache.. Maven plugin. AbstractMojo

@Mojo(name = "echo",defaultPhase = LifecyclePhase.PACKAGE)
public class EchoMojo extends AbstractMojo {


    @Parameter
    private String applicationName;

    public void execute(a) throws MojoExecutionException, MojoFailureException {

        getLog().info("echo-->"+ applicationName); }}Copy the code

@mojo tells Maven that this is not a normal Java class, but a Mojo plug-in class. DefaultPhase specifies which phase of maven’s life cycle triggers execution by default

Plug-ins can trigger execution in the following phasesThe @parameter function does two things

  • 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.

The main features are hooks that allow users to adjust the actions of plug-ins to suit their needs and to extract parameters from POM files. This parameter can be extracted from the configration tag of the plug-in

3. Install the written plug-in to the local repository

Execute the command

mvn clean install
Copy the code

The following exceptions may be reported during the execution

org.apache.maven.plugins:maven-plugin-plugin:3.2:descriptor (default-descriptor)
Copy the code

Maven-plugin-plugin version is not specified, so the default is 3.2, which does not fit the current code, so specify the version and add it to the POM file

 <build>
         <plugins>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-plugin-plugin</artifactId>
                 <version>3.5</version>
             </plugin>
         </plugins>
     </build>
Copy the code

How to use custom plug-ins in a project

Take the example of the plug-in for the sample project, introduced in POM.xml

 <build>
        <plugins>
            <plugin>
                <groupId>com.github.lybgeek</groupId>
                <artifactId>echo-maven-plugin</artifactId>
                <version>1.0 the SNAPSHOT</version>
                <configuration>
                    <applicationName>springboot-echo</applicationName>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>echo</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

Copy the code

Execute MVN Clean Package

conclusion

Maven plugins can be thought of as Maven’s hook functions during the execution lifecycle. If we trigger something during the compilation, packaging, installation, deployment, etc., we can consider implementing a Maven plugin. Such as generating offline interface documentation

In fact, the official website also provides a detailed development guide for developing Maven plug-ins. If you are interested, you can check out the following link

Maven.apache.org/guides/plug…

The demo link

Github.com/lyb-geek/sp…