Maven自定义插件以及使用


  简单maven 插件项目的创建以及使用。

  参考: https://maven.apache.org/guides/plugin/guide-java-plugin-development.html

  https://maven.apache.org/plugin-tools/index.html

  官网建议插件名称的起名为-maven-plugin

  有两种方式, 第一种是注解方式; 第二种是文档的方式。 下面研究其使用。

1. 注解方式

  参考: https://maven.apache.org/plugin-tools/maven-plugin-tools-annotations/index.html

1. IDEA 新建项目pom 文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <modelVersion>4.0.0modelVersion>

    <groupId>cn.qz.cloudgroupId>
    <artifactId>my-mvn-pluginartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
    properties>

    
    <packaging>maven-pluginpackaging>

    <dependencies>
        
        <dependency>
            <groupId>org.apache.maven.plugin-toolsgroupId>
            <artifactId>maven-plugin-annotationsartifactId>
            <version>3.6.2version>
            <optional>trueoptional>
            
        dependency>
        <dependency>
            <groupId>org.apache.mavengroupId>
            <artifactId>maven-coreartifactId>
            <version>3.3.9version>
        dependency>
    dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-plugin-pluginartifactId>
                <version>3.6.2version>
            plugin>
        plugins>
    build>

project>

  注意打包方式为maven-plugin

 2. 标准注解如下:

import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.InstantiationStrategy;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Settings;

/**
 * Mojo Description. @Mojo( name = "" ) is the minimal required annotation.
 * @since 
 * @deprecated 
 */
@Mojo( name = "",
        aggregator = <false|true>,
        configurator = "",
        executionStrategy = "", // (unsupported since Maven 3.0)
        inheritByDefault = <true|false>, // (unsupported since Maven 3.0)
        instantiationStrategy = InstantiationStrategy.,
        defaultPhase = LifecyclePhase.,
        requiresDependencyResolution = ResolutionScope.,
        requiresDependencyCollection = ResolutionScope., // (since Maven 3.0)
        requiresDirectInvocation = <false|true>, // (unsupported since Maven 3.0)
        requiresOnline = <false|true>,
        requiresProject = <true|false>,
        requiresReports = <false|true>, // (unsupported since Maven 3.0)
        threadSafe = <false|true> ) // (since Maven 3.0)
@Execute( goal = "",
        phase = LifecyclePhase.,
        lifecycle = "" )
public class MyMojo
        extends AbstractMojo
{
    /**
     * @since 
     * @deprecated 
     */
    @Parameter( name = "parameter",
            alias = "myAlias",
            property = "a.property",
            defaultValue = "an expression, possibly with ${variables}",
            readonly = <false|true>,
            required = <false|true> )
    private String parameter;

    @Component( role = MyComponentExtension.class,
            hint = "..." )
    private MyComponent component;

    // sample objects taken from Maven API through PluginParameterExpressionEvaluator

    @Parameter( defaultValue = "${session}", readonly = true )
    private MavenSession session;

    @Parameter( defaultValue = "${project}", readonly = true )
    private MavenProject project;

    @Parameter( defaultValue = "${mojoExecution}", readonly = true )
    private MojoExecution mojo;

    @Parameter( defaultValue = "${plugin}", readonly = true ) // Maven 3 only
    private PluginDescriptor plugin;

    @Parameter( defaultValue = "${settings}", readonly = true )
    private Settings settings;

    @Parameter( defaultValue = "${project.basedir}", readonly = true )
    private File basedir;

    @Parameter( defaultValue = "${project.build.directory}", readonly = true )
    private File target;

    public void execute()
    {
        ...
    }
}

  可以看到有许多内置的属性以及对象,也就是maven 可以直接获取的相关变量。

1. org.apache.maven.plugins.annotations.Mojo 注解如下:

package org.apache.maven.plugins.annotations;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * This annotation will mark your class as a Mojo (ie. goal in a Maven plugin).
 *
 * @author Olivier Lamy
 * @since 3.0
 */
@Documented
@Retention( RetentionPolicy.CLASS )
@Target( ElementType.TYPE )
@Inherited
public @interface Mojo
{
    /**
     * goal name (required).
     * @return the goal name
     */
    String name();

    /**
     * default phase to bind your mojo.
     * @return the default phase
     */
    LifecyclePhase defaultPhase() default LifecyclePhase.NONE;

    /**
     * the required dependency resolution scope.
     * @return the required dependency resolution scope
     */
    ResolutionScope requiresDependencyResolution() default ResolutionScope.NONE;

    /**
     * the required dependency collection scope.
     * @return the required dependency collection scope 
     */
    ResolutionScope requiresDependencyCollection() default ResolutionScope.NONE;

    /**
     * your Mojo instantiation strategy. (Only per-lookup and singleton are supported)
     * @return the instantiation strategy
     */
    InstantiationStrategy instantiationStrategy() default InstantiationStrategy.PER_LOOKUP;

    /**
     * execution strategy: once-per-session or always.
     * @return once-per-session or always
     *
     * @deprecated unused
     */
    @Deprecated
    String executionStrategy() default "once-per-session";

    /**
     * does your mojo requires a project to be executed?
     * @return requires a project
     */
    boolean requiresProject() default true;

    /**
     * does your mojo requires a reporting context to be executed?
     * @return requires a reporting context
     *
     * @deprecated unused
     */
    @Deprecated
    boolean requiresReports() default false;

    /**
     * if the Mojo uses the Maven project and its child modules.
     * @return uses the Maven project and its child modules
     */
    boolean aggregator() default false;

    /**
     * can this Mojo be invoked directly only?
     * @return invoked directly only
     *
     * @deprecated unused
     */
    @Deprecated
    boolean requiresDirectInvocation() default false;

    /**
     * does this Mojo need to be online to be executed?
     * @return need to be online
     */
    boolean requiresOnline() default false;

    /**
     * @deprecated unused
     */
    @Deprecated
    boolean inheritByDefault() default true;

    /**
     * own configurator class.
     * @return own configurator class
     */
    String configurator() default "";

    /**
     * is your mojo thread safe (since Maven 3.x)?
     * @return is thread safe
     */
    boolean threadSafe() default false;
}

2. org.apache.maven.plugins.annotations.LifecyclePhase 阶段枚举如下:

package org.apache.maven.plugins.annotations;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * Lifecycle phases.
 * @author Olivier Lamy
 * @since 3.0
 */
public enum LifecyclePhase
{

    VALIDATE( "validate" ),
    INITIALIZE( "initialize" ),
    GENERATE_SOURCES( "generate-sources" ),
    PROCESS_SOURCES( "process-sources" ),
    GENERATE_RESOURCES( "generate-resources" ),
    PROCESS_RESOURCES( "process-resources" ),
    COMPILE( "compile" ),
    PROCESS_CLASSES( "process-classes" ),
    GENERATE_TEST_SOURCES( "generate-test-sources" ),
    PROCESS_TEST_SOURCES( "process-test-sources" ),
    GENERATE_TEST_RESOURCES( "generate-test-resources" ),
    PROCESS_TEST_RESOURCES( "process-test-resources" ),
    TEST_COMPILE( "test-compile" ),
    PROCESS_TEST_CLASSES( "process-test-classes" ),
    TEST( "test" ),
    PREPARE_PACKAGE( "prepare-package" ),
    PACKAGE( "package" ),
    PRE_INTEGRATION_TEST( "pre-integration-test" ),
    INTEGRATION_TEST( "integration-test" ),
    POST_INTEGRATION_TEST( "post-integration-test" ),
    VERIFY( "verify" ),
    INSTALL( "install" ),
    DEPLOY( "deploy" ),

    PRE_CLEAN( "pre-clean" ),
    CLEAN( "clean" ),
    POST_CLEAN( "post-clean" ),

    PRE_SITE( "pre-site" ),
    SITE( "site" ),
    POST_SITE( "post-site" ),
    SITE_DEPLOY( "site-deploy" ),

    NONE( "" );

    private final String id;

    LifecyclePhase( String id )
    {
        this.id = id;
    }

    public String id()
    {
        return this.id;
    }

}

3.  新建第一个Mojo

cn.qz.MyMojo

package cn.qz;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Settings;

import java.io.File;
import java.util.List;

/**
 * Mojo Description. @Mojo( name = "" ) is the minimal required annotation.
 *
 * @since 
 * @deprecated 
 */
@Mojo(name = "mvtest", defaultPhase = LifecyclePhase.COMPILE) // (since Maven 3.0)
public class MyMojo extends AbstractMojo {
    /**
     * @since 
     * @deprecated 
     */
    @Parameter(name = "parameter",
            alias = "myAlias",
            property = "a.property",
            defaultValue = "an expression, possibly with ${variables}",
            readonly = true,
            required = true)
    private String parameter;

    @Parameter
    private List multiParams;

    // sample objects taken from Maven API through PluginParameterExpressionEvaluator

    @Parameter(defaultValue = "${session}", readonly = true)
    private MavenSession session;

    @Parameter(defaultValue = "${project}", readonly = true)
    private MavenProject project;

    @Parameter(defaultValue = "${mojoExecution}", readonly = true)
    private MojoExecution mojo;

    @Parameter(defaultValue = "${plugin}", readonly = true) // Maven 3 only
    private PluginDescriptor plugin;

    @Parameter(defaultValue = "${settings}", readonly = true)
    private Settings settings;

    @Parameter(defaultValue = "${project.basedir}", readonly = true)
    private File basedir;

    @Parameter(defaultValue = "${project.build.directory}", readonly = true)
    private File target;

    public void execute() {
        String groupId = project.getGroupId();
        String artifactId = project.getArtifactId();
        getLog().info("------------------------------< " + groupId + ":" + artifactId + " > start------------------------------");
        getLog().info("target: " + target.getAbsolutePath());
        getLog().info("basedir: " + basedir.getAbsolutePath());
        getLog().info("settings: " + settings);
        getLog().info("plugin: " + plugin);
        getLog().info("mojo: " + mojo);
        getLog().info("project: " + project);
        getLog().info("session: " + session);
        getLog().info("parameter: " + parameter);
        for (int i = 0; i < multiParams.size(); i++) {
            getLog().info("multiParams.get(i): " + multiParams.get(i));
        }
        getLog().info("------------------------------< " + groupId + ":" + artifactId + " > end------------------------------");
    }
}

4. install 生成插件包

5. 另一个项目使用该插件

(1) 使用默认参数:

            <plugin>
                <groupId>cn.qz.cloudgroupId>
                <artifactId>my-mvn-pluginartifactId>
                <version>1.0-SNAPSHOTversion>
                <executions>
                    <execution>
                        <goals>
                            <goal>mvtestgoal>
                        goals>
                    execution>
                executions>
            plugin>

执行compile 后, 发现会失败。 因为插件中的 multiParams 未校验直接使用, 如果不传导致空指针。报错如下:(也就是maven插件内部报错会导致后续流程失败)

Failed to execute goal cn.qz.cloud:my-mvn-plugin:1.0-SNAPSHOT:mvtest (default) on project xm: Execution default of goal cn.qz.cloud:my-mvn-plugin:1.0-SNAPSHOT:mvtest failed.

(2) 修改传递一些参数:

            <plugin>
                <groupId>cn.qz.cloudgroupId>
                <artifactId>my-mvn-pluginartifactId>
                <version>1.0-SNAPSHOTversion>
                <executions>
                    <execution>
                        <goals>
                            <goal>mvtestgoal>
                        goals>
                        
                        <configuration>
                            <myAlias>
                                111222333444
                            myAlias>
                            <multiParams>
                                <multiParam>11multiParam>
                                <multiParam>22multiParam>
                                <multiParam>33multiParam>
                                <multiParam>44multiParam>
                            multiParams>
                        configuration>
                    execution>
                executions>
            plugin>

该项目执行compile日志如下:

[INFO] ------------------------------< cn.qz:xm > start------------------------------
[INFO] target: D:\study\bs-chart\vue-boot-chart\chart-server\target
[INFO] basedir: D:\study\bs-chart\vue-boot-chart\chart-server
[INFO] settings: org.apache.maven.execution.SettingsAdapter@7ce7e83c
[INFO] plugin: Component Descriptor: role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.MyMojo', role hint: 'cn.qz.cloud:my-mvn-plugin:1.0-SNAPSHOT:mvtest'
---
[INFO] mojo: cn.qz.cloud:my-mvn-plugin:1.0-SNAPSHOT:mvtest {execution: default}
[INFO] project: MavenProject: cn.qz:xm:0.0.1-SNAPSHOT @ D:\study\bs-chart\vue-boot-chart\chart-server\pom.xml
[INFO] session: org.apache.maven.execution.MavenSession@4a05d8ae
[INFO] parameter: 111222333444
[INFO] multiParams.get(i): 11
[INFO] multiParams.get(i): 22
[INFO] multiParams.get(i): 33
[INFO] multiParams.get(i): 44
[INFO] ------------------------------< cn.qz:xm > end------------------------------

6. 再加一个Mojo, 编译的时候生成一个编译时间文件

package cn.qz;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Mojo(name = "generate", defaultPhase = LifecyclePhase.COMPILE)
public class GenarateProperties extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true)
    private MavenProject project;

    @Parameter(defaultValue = "buildtime.txt")
    private String fileName;

    @Parameter(defaultValue = "yyyy-MM-dd HH:mm:ss")
    private String dateFormat;

    public void execute() {
        String groupId = project.getGroupId();
        String artifactId = project.getArtifactId();
        getLog().info("====== " + groupId + ":" + artifactId + " > generate start======");
        // 生成一个properties 文件记录编译时间
        String directory = project.getBuild().getDirectory();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        String formatedDate = simpleDateFormat.format(new Date());
        File generateFile = new File(new File(directory), fileName);
        try {
            new FileOutputStream(generateFile).write(formatedDate.getBytes());
            getLog().info("write file: " + generateFile.getAbsolutePath());
        } catch (IOException e) {
            getLog().error("write error", e);
            throw new RuntimeException(e);
        }
        getLog().info("====== " + groupId + ":" + artifactId + " > generate end======");
    }

}

7. 测试上面命令

(1) 另一个项目pom 增加插件

            
                cn.qz.cloud
                my-mvn-plugin
                1.0-SNAPSHOT
                
                    
                        
                            generate
                        
                    
                
            

执行compile 后查看日志如下:

[INFO] --- my-mvn-plugin:1.0-SNAPSHOT:generate (default) @ xm ---
[INFO] ====== cn.qz:xm > generate start======
[INFO] write file: D:\study\bs-chart\vue-boot-chart\chart-server\target\buildtime.txt
[INFO] ====== cn.qz:xm > generate end======

(2) 修改执行两个goal

            
                cn.qz.cloud
                my-mvn-plugin
                1.0-SNAPSHOT
                
                    
                        
                            generate
                            mvtest
                        
                        
                        
                            
                                11
                                22
                                33
                                44
                            
                        
                    
                
            

日志如下:

[INFO] --- my-mvn-plugin:1.0-SNAPSHOT:generate (default) @ xm ---
[INFO] ====== cn.qz:xm > generate start======
[INFO] write file: D:\study\bs-chart\vue-boot-chart\chart-server\target\buildtime.txt
[INFO] ====== cn.qz:xm > generate end======
[INFO] 
[INFO] --- my-mvn-plugin:1.0-SNAPSHOT:mvtest (default) @ xm ---
[INFO] ------------------------------< cn.qz:xm > start------------------------------
[INFO] target: D:\study\bs-chart\vue-boot-chart\chart-server\target
[INFO] basedir: D:\study\bs-chart\vue-boot-chart\chart-server
[INFO] settings: org.apache.maven.execution.SettingsAdapter@3c904f1e
[INFO] plugin: Component Descriptor: role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.GenarateProperties', role hint: 'cn.qz.cloud:my-mvn-plugin:1.0-SNAPSHOT:generate'
role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.MyMojo', role hint: 'cn.qz.cloud:my-mvn-plugin:1.0-SNAPSHOT:mvtest'
---
[INFO] mojo: cn.qz.cloud:my-mvn-plugin:1.0-SNAPSHOT:mvtest {execution: default}
[INFO] project: MavenProject: cn.qz:xm:0.0.1-SNAPSHOT @ D:\study\bs-chart\vue-boot-chart\chart-server\pom.xml
[INFO] session: org.apache.maven.execution.MavenSession@4eb30d44
[INFO] parameter: an expression, possibly with ${variables}
[INFO] multiParams.get(i): 11
[INFO] multiParams.get(i): 22
[INFO] multiParams.get(i): 33
[INFO] multiParams.get(i): 44
[INFO] ------------------------------< cn.qz:xm > end------------------------------

2. 文档方式使用

  参考: https://maven.apache.org/plugin-tools/maven-plugin-tools-java/index.html

 1. pom 如下

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <modelVersion>4.0.0modelVersion>

    <groupId>cn.qz.cloudgroupId>
    <artifactId>my-mvn-pluginartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
    properties>

    
    <packaging>maven-pluginpackaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.mavengroupId>
            <artifactId>maven-plugin-apiartifactId>
            <version>3.6.2version>
        dependency>
        <dependency>
            <groupId>org.apache.mavengroupId>
            <artifactId>maven-coreartifactId>
            <version>3.3.9version>
        dependency>
    dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-plugin-pluginartifactId>
                <version>3.6.2version>
            plugin>
        plugins>
    build>

project>

2. Mojo 如下

package cn.qz;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.project.MavenProject;

/**
 * 使用文档的方式
 *
 * @goal print
 * @phase compile
 */
public class PrintMojo extends AbstractMojo {


    /**
     * @parameter expression = "${project}"
     */
    private MavenProject project;

    public void execute() {
        String groupId = project.getGroupId();
        String artifactId = project.getArtifactId();
        getLog().info("------------------------------< " + groupId + ":" + artifactId + " > start------------------------------");
        getLog().info("------------------------------< " + groupId + ":" + artifactId + " > end------------------------------");
    }

}

3. 打包后测试:

1. pom 增加

            <plugin>
                <groupId>cn.qz.cloudgroupId>
                <artifactId>my-mvn-pluginartifactId>
                <version>1.0-SNAPSHOTversion>
                <executions>
                    <execution>
                        <goals>
                            <goal>printgoal>
                        goals>
                    execution>
                executions>
            plugin>

2. 执行compile后日志如下

[INFO] --- my-mvn-plugin:1.0-SNAPSHOT:print (default) @ xm ---
[INFO] ------------------------------< cn.qz:xm > start------------------------------
[INFO] ------------------------------< cn.qz:xm > end------------------------------

 3.  全局设置

1. 插件项目修改

1. 修改cn.qz.MyMojo 默认阶段绑定为compile

package cn.qz;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Settings;

import java.io.File;
import java.util.List;

@Mojo(name = "mvtest", defaultPhase = LifecyclePhase.COMPILE) // (since Maven 3.0)
public class MyMojo extends AbstractMojo {
    
    @Parameter(name = "parameter",
            alias = "myAlias",
            property = "a.property",
            defaultValue = "an expression, possibly with ${variables}",
            readonly = true,
            required = true)
    private String parameter;

    @Parameter
    private List multiParams;

    // sample objects taken from Maven API through PluginParameterExpressionEvaluator

    @Parameter(defaultValue = "${session}", readonly = true)
    private MavenSession session;

    @Parameter(defaultValue = "${project}", readonly = true)
    private MavenProject project;

    @Parameter(defaultValue = "${mojoExecution}", readonly = true)
    private MojoExecution mojo;

    @Parameter(defaultValue = "${plugin}", readonly = true) // Maven 3 only
    private PluginDescriptor plugin;

    @Parameter(defaultValue = "${settings}", readonly = true)
    private Settings settings;

    @Parameter(defaultValue = "${project.basedir}", readonly = true)
    private File basedir;

    @Parameter(defaultValue = "${project.build.directory}", readonly = true)
    private File target;

    public void execute() {
        String groupId = project.getGroupId();
        String artifactId = project.getArtifactId();
        getLog().info("------------------------------< " + groupId + ":" + artifactId + " > start------------------------------");
        getLog().info("target: " + target.getAbsolutePath());
        getLog().info("basedir: " + basedir.getAbsolutePath());
        getLog().info("settings: " + settings);
        getLog().info("plugin: " + plugin);
        getLog().info("mojo: " + mojo);
        getLog().info("project: " + project);
        getLog().info("session: " + session);
        getLog().info("parameter: " + parameter);
        if (multiParams != null) {
            for (int i = 0; i < multiParams.size(); i++) {
                getLog().info("multiParams.get(i): " + multiParams.get(i));
            }
        }
        getLog().info("mojo.getLifecyclePhase(): " + mojo.getLifecyclePhase());
        getLog().info("------------------------------< " + groupId + ":" + artifactId + " > end------------------------------");
    }
}

2. 把上面两种形式的三个插件都加到项目,并且修改项目前缀。 pom 修改如下:

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <modelVersion>4.0.0modelVersion>

    <groupId>cn.qz.cloudgroupId>
    <artifactId>my-mvn-pluginartifactId>
    <version>2.0-SNAPSHOTversion>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
    properties>

    
    <packaging>maven-pluginpackaging>

    <dependencies>
        
        <dependency>
            <groupId>org.apache.maven.plugin-toolsgroupId>
            <artifactId>maven-plugin-annotationsartifactId>
            <version>3.6.2version>
            <optional>trueoptional>
            
        dependency>
        <dependency>
            <groupId>org.apache.mavengroupId>
            <artifactId>maven-coreartifactId>
            <version>3.3.9version>
        dependency>
    dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-plugin-pluginartifactId>
                <version>3.6.2version>
                <configuration>
                    
                    <goalPrefix>mpgoalPrefix>
                configuration>
            plugin>
        plugins>
    build>

project>

2. 另一个项目

(1) pom引入插件

            <plugin>
                <groupId>cn.qz.cloudgroupId>
                <artifactId>my-mvn-pluginartifactId>
                <version>2.0-SNAPSHOTversion>
            plugin>

(2) IDEAmaven插件查看

 (3) 执行:

  用户可以通过两种方式调用Maven插件目标。第一种方式是将插件目标与生命周期阶段(lifecycle phase)绑定,这样用户在命令行只是输入生命周期阶段而已,例如Maven默认将maven-compiler-plugin的compile目标与compile生命周期阶段绑定,因此命令mvn compile实际上是先定位到compile这一生命周期阶段,然后再根据绑定关系调用maven-compiler-plugin的compile目标。第二种方式是直接在命令行指定要执行的插件目标,例如mvnarchetype:generate 就表示调用maven-archetype-plugin的generate目标,这种带冒号的调用方式与生命周期无关。

1》第一种:

mvn [plugin-name]:[goal-name]

  该命令的意思是:执行plugin-name插件的 goal-name 目标(或者称为动作)。

测试如下: 一种是插件全称, 一种是简称

qiaoliqiang@XXX-NC01 MINGW64 /d/study/bs-chart/vue-boot-chart/chart-server (master)
$ mvn cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:mvtest
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building blog 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- my-mvn-plugin:2.0-SNAPSHOT:mvtest (default-cli) @ xm ---
[INFO] ------------------------------< cn.qz:xm > start------------------------------
[INFO] target: D:\study\bs-chart\vue-boot-chart\chart-server\target
[INFO] basedir: D:\study\bs-chart\vue-boot-chart\chart-server
[INFO] settings: org.apache.maven.execution.SettingsAdapter@7859e786
[INFO] plugin: Component Descriptor: role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.GenarateProperties', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:generate'
role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.MyMojo', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:mvtest'
role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.PrintMojo', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:print'
---
[INFO] mojo: cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:mvtest {execution: default-cli}
[INFO] project: MavenProject: cn.qz:xm:0.0.1-SNAPSHOT @ D:\study\bs-chart\vue-boot-chart\chart-server\pom.xml
[INFO] session: org.apache.maven.execution.MavenSession@285d851a
[INFO] parameter: an expression, possibly with ${variables}
[INFO] mojo.getLifecyclePhase(): null
[INFO] ------------------------------< cn.qz:xm > end------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.123 s
[INFO] Finished at: 2021-12-07T17:11:22+08:00
[INFO] Final Memory: 12M/241M
[INFO] ------------------------------------------------------------------------

qiaoliqiang@XXX-NC01 MINGW64 /d/study/bs-chart/vue-boot-chart/chart-server (master)
$ mvn mp:mvtest
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building blog 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- my-mvn-plugin:2.0-SNAPSHOT:mvtest (default-cli) @ xm ---
[INFO] ------------------------------< cn.qz:xm > start------------------------------
[INFO] target: D:\study\bs-chart\vue-boot-chart\chart-server\target
[INFO] basedir: D:\study\bs-chart\vue-boot-chart\chart-server
[INFO] settings: org.apache.maven.execution.SettingsAdapter@62923ee6
[INFO] plugin: Component Descriptor: role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.GenarateProperties', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:generate'
role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.MyMojo', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:mvtest'
role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.PrintMojo', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:print'
---
[INFO] mojo: cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:mvtest {execution: default-cli}
[INFO] project: MavenProject: cn.qz:xm:0.0.1-SNAPSHOT @ D:\study\bs-chart\vue-boot-chart\chart-server\pom.xml
[INFO] session: org.apache.maven.execution.MavenSession@4089713
[INFO] parameter: an expression, possibly with ${variables}
[INFO] mojo.getLifecyclePhase(): null
[INFO] ------------------------------< cn.qz:xm > end------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.212 s
[INFO] Finished at: 2021-12-07T17:11:34+08:00
[INFO] Final Memory: 15M/304M
[INFO] ------------------------------------------------------------------------

2》 第二种: 绑定阶段

  修改pom中插件属性

            <plugin>
                <groupId>cn.qz.cloudgroupId>
                <artifactId>my-mvn-pluginartifactId>
                <version>2.0-SNAPSHOTversion>
                <executions>
                    <execution>
                        
                        <goals>
                            <goal>mvtestgoal>
                        goals>
                    execution>
                executions>
            plugin>

测试一: 可以看到默认是compile 阶段走mvtest 任务,也就是我们设置的默认的阶段

qiaoliqiang@XXX-NC01 MINGW64 /d/study/bs-chart/vue-boot-chart/chart-server (master)
$ mvn clean
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building blog 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ xm ---
[INFO] Deleting D:\study\bs-chart\vue-boot-chart\chart-server\target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.147 s
[INFO] Finished at: 2021-12-07T17:24:12+08:00
[INFO] Final Memory: 13M/241M
[INFO] ------------------------------------------------------------------------

qiaoliqiang@XXX-NC01 MINGW64 /d/study/bs-chart/vue-boot-chart/chart-server (master)
$ mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building blog 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ xm ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO] Copying 4 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ xm ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 119 source files to D:\study\bs-chart\vue-boot-chart\chart-server\target\classes
[INFO] /D:/study/bs-chart/vue-boot-chart/chart-server/src/main/java/com/xm/ggn/bean/AbstractEntity.java: ?Щ????????????????????? API??
[INFO] /D:/study/bs-chart/vue-boot-chart/chart-server/src/main/java/com/xm/ggn/bean/AbstractEntity.java: ?й???????, ????? -Xlint:deprecation ???±???
[INFO] /D:/study/bs-chart/vue-boot-chart/chart-server/src/main/java/com/xm/ggn/config/redis/RedisCacheConfig.java: ?Щ????????????δ????????????????
[INFO] /D:/study/bs-chart/vue-boot-chart/chart-server/src/main/java/com/xm/ggn/config/redis/RedisCacheConfig.java: ?й???????, ????? -Xlint:unchecked ???±???
[INFO]
[INFO] --- my-mvn-plugin:2.0-SNAPSHOT:mvtest (default) @ xm ---
[INFO] ------------------------------< cn.qz:xm > start------------------------------
[INFO] target: D:\study\bs-chart\vue-boot-chart\chart-server\target
[INFO] basedir: D:\study\bs-chart\vue-boot-chart\chart-server
[INFO] settings: org.apache.maven.execution.SettingsAdapter@7ad9ed91
[INFO] plugin: Component Descriptor: role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.GenarateProperties', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:generate'
role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.MyMojo', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:mvtest'
role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.PrintMojo', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:print'
---
[INFO] mojo: cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:mvtest {execution: default}
[INFO] project: MavenProject: cn.qz:xm:0.0.1-SNAPSHOT @ D:\study\bs-chart\vue-boot-chart\chart-server\pom.xml
[INFO] session: org.apache.maven.execution.MavenSession@60362b7
[INFO] parameter: an expression, possibly with ${variables}
[INFO] mojo.getLifecyclePhase(): compile
[INFO] ------------------------------< cn.qz:xm > end------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 15.866 s
[INFO] Finished at: 2021-12-07T17:24:35+08:00
[INFO] Final Memory: 52M/449M
[INFO] ------------------------------------------------------------------------

测试二: 修改阶段为clean, 然后执行clean 命令可以看到会走mvtest 任务

pom 中修改阶段为clean 阶段

            <plugin>
                <groupId>cn.qz.cloudgroupId>
                <artifactId>my-mvn-pluginartifactId>
                <version>2.0-SNAPSHOTversion>
                <executions>
                    <execution>
                        
                        <phase>
                            clean
                        phase>
                        <goals>
                            <goal>mvtestgoal>
                        goals>
                    execution>
                executions>
            plugin>

测试结果:

qiaoliqiang@XXX-NC01 MINGW64 /d/study/bs-chart/vue-boot-chart/chart-server (master)
$ mvn clean
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building blog 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ xm ---
[INFO] Deleting D:\study\bs-chart\vue-boot-chart\chart-server\target
[INFO]
[INFO] --- my-mvn-plugin:2.0-SNAPSHOT:mvtest (default) @ xm ---
[INFO] ------------------------------< cn.qz:xm > start------------------------------
[INFO] target: D:\study\bs-chart\vue-boot-chart\chart-server\target
[INFO] basedir: D:\study\bs-chart\vue-boot-chart\chart-server
[INFO] settings: org.apache.maven.execution.SettingsAdapter@578524c3
[INFO] plugin: Component Descriptor: role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.GenarateProperties', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:generate'
role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.MyMojo', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:mvtest'
role: 'org.apache.maven.plugin.Mojo', implementation: 'cn.qz.PrintMojo', role hint: 'cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:print'
---
[INFO] mojo: cn.qz.cloud:my-mvn-plugin:2.0-SNAPSHOT:mvtest {execution: default}
[INFO] project: MavenProject: cn.qz:xm:0.0.1-SNAPSHOT @ D:\study\bs-chart\vue-boot-chart\chart-server\pom.xml
[INFO] session: org.apache.maven.execution.MavenSession@64c2b546
[INFO] parameter: an expression, possibly with ${variables}
[INFO] mojo.getLifecyclePhase(): clean
[INFO] ------------------------------< cn.qz:xm > end------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.509 s
[INFO] Finished at: 2021-12-07T17:28:36+08:00
[INFO] Final Memory: 15M/241M
[INFO] ------------------------------------------------------------------------

qiaoliqiang@XXX-NC01 MINGW64 /d/study/bs-chart/vue-boot-chart/chart-server (master)
$ mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building blog 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ xm ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO] Copying 4 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ xm ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 119 source files to D:\study\bs-chart\vue-boot-chart\chart-server\target\classes
[INFO] /D:/study/bs-chart/vue-boot-chart/chart-server/src/main/java/com/xm/ggn/bean/AbstractEntity.java: ?Щ????????????????????? API??
[INFO] /D:/study/bs-chart/vue-boot-chart/chart-server/src/main/java/com/xm/ggn/bean/AbstractEntity.java: ?й???????, ????? -Xlint:deprecation ???±???
[INFO] /D:/study/bs-chart/vue-boot-chart/chart-server/src/main/java/com/xm/ggn/config/redis/RedisCacheConfig.java: ?Щ????????????δ????????????????
[INFO] /D:/study/bs-chart/vue-boot-chart/chart-server/src/main/java/com/xm/ggn/config/redis/RedisCacheConfig.java: ?й???????, ????? -Xlint:unchecked ???±???
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 15.586 s
[INFO] Finished at: 2021-12-07T17:29:36+08:00
[INFO] Final Memory: 51M/449M
[INFO] ------------------------------------------------------------------------

补充: 插件生成jar 之后, 有相关描述

比如 my-mvn-plugin-2.0-SNAPSHOT.jar!\META-INF\maven\plugin.xml 有相关mojo 以及参数的描述,内容如下

<?xml version="1.0" encoding="UTF-8"?>



<plugin>
  <name>my-mvn-pluginname>
  <description>description>
  <groupId>cn.qz.cloudgroupId>
  <artifactId>my-mvn-pluginartifactId>
  <version>2.0-SNAPSHOTversion>
  <goalPrefix>mpgoalPrefix>
  <isolatedRealm>falseisolatedRealm>
  <inheritedByDefault>trueinheritedByDefault>
  <mojos>
    <mojo>
      <goal>generategoal>
      <requiresDirectInvocation>falserequiresDirectInvocation>
      <requiresProject>truerequiresProject>
      <requiresReports>falserequiresReports>
      <aggregator>falseaggregator>
      <requiresOnline>falserequiresOnline>
      <inheritedByDefault>trueinheritedByDefault>
      <phase>packagephase>
      <implementation>cn.qz.GenaratePropertiesimplementation>
      <language>javalanguage>
      <instantiationStrategy>per-lookupinstantiationStrategy>
      <executionStrategy>once-per-sessionexecutionStrategy>
      <threadSafe>falsethreadSafe>
      <parameters>
        <parameter>
          <name>dateFormatname>
          <type>java.lang.Stringtype>
          <required>falserequired>
          <editable>trueeditable>
          <description>description>
        parameter>
        <parameter>
          <name>fileNamename>
          <type>java.lang.Stringtype>
          <required>falserequired>
          <editable>trueeditable>
          <description>description>
        parameter>
        <parameter>
          <name>projectname>
          <type>org.apache.maven.project.MavenProjecttype>
          <required>falserequired>
          <editable>falseeditable>
          <description>description>
        parameter>
      parameters>
      <configuration>
        <dateFormat implementation="java.lang.String" default-value="yyyy-MM-dd HH:mm:ss"/>
        <fileName implementation="java.lang.String" default-value="buildtime.txt"/>
        <project implementation="org.apache.maven.project.MavenProject" default-value="${project}"/>
      configuration>
    mojo>
    <mojo>
      <goal>mvtestgoal>
      <requiresDirectInvocation>falserequiresDirectInvocation>
      <requiresProject>truerequiresProject>
      <requiresReports>falserequiresReports>
      <aggregator>falseaggregator>
      <requiresOnline>falserequiresOnline>
      <inheritedByDefault>trueinheritedByDefault>
      <phase>compilephase>
      <implementation>cn.qz.MyMojoimplementation>
      <language>javalanguage>
      <instantiationStrategy>per-lookupinstantiationStrategy>
      <executionStrategy>once-per-sessionexecutionStrategy>
      <threadSafe>falsethreadSafe>
      <parameters>
        <parameter>
          <name>basedirname>
          <type>java.io.Filetype>
          <required>falserequired>
          <editable>falseeditable>
          <description>description>
        parameter>
        <parameter>
          <name>mojoname>
          <type>org.apache.maven.plugin.MojoExecutiontype>
          <required>falserequired>
          <editable>falseeditable>
          <description>description>
        parameter>
        <parameter>
          <name>multiParamsname>
          <type>java.util.Listtype>
          <required>falserequired>
          <editable>trueeditable>
          <description>description>
        parameter>
        <parameter>
          <name>parametername>
          <alias>myAliasalias>
          <type>java.lang.Stringtype>
          <since><since-text>since>
          <deprecated><deprecated-text>deprecated>
          <required>truerequired>
          <editable>falseeditable>
          <description>description>
        parameter>
        <parameter>
          <name>pluginname>
          <type>org.apache.maven.plugin.descriptor.PluginDescriptortype>
          <required>falserequired>
          <editable>falseeditable>
          <description>description>
        parameter>
        <parameter>
          <name>projectname>
          <type>org.apache.maven.project.MavenProjecttype>
          <required>falserequired>
          <editable>falseeditable>
          <description>description>
        parameter>
        <parameter>
          <name>sessionname>
          <type>org.apache.maven.execution.MavenSessiontype>
          <required>falserequired>
          <editable>falseeditable>
          <description>description>
        parameter>
        <parameter>
          <name>settingsname>
          <type>org.apache.maven.settings.Settingstype>
          <required>falserequired>
          <editable>falseeditable>
          <description>description>
        parameter>
        <parameter>
          <name>targetname>
          <type>java.io.Filetype>
          <required>falserequired>
          <editable>falseeditable>
          <description>description>
        parameter>
      parameters>
      <configuration>
        <basedir implementation="java.io.File" default-value="${project.basedir}"/>
        <mojo implementation="org.apache.maven.plugin.MojoExecution" default-value="${mojoExecution}"/>
        <parameter implementation="java.lang.String" default-value="an expression, possibly with ${variables}">${a.property}parameter>
        <plugin implementation="org.apache.maven.plugin.descriptor.PluginDescriptor" default-value="${plugin}"/>
        <project implementation="org.apache.maven.project.MavenProject" default-value="${project}"/>
        <session implementation="org.apache.maven.execution.MavenSession" default-value="${session}"/>
        <settings implementation="org.apache.maven.settings.Settings" default-value="${settings}"/>
        <target implementation="java.io.File" default-value="${project.build.directory}"/>
      configuration>
    mojo>
    <mojo>
      <goal>printgoal>
      <description>使用文档的方式description>
      <requiresDirectInvocation>falserequiresDirectInvocation>
      <requiresProject>truerequiresProject>
      <requiresReports>falserequiresReports>
      <aggregator>falseaggregator>
      <requiresOnline>falserequiresOnline>
      <inheritedByDefault>trueinheritedByDefault>
      <phase>initializephase>
      <implementation>cn.qz.PrintMojoimplementation>
      <language>javalanguage>
      <instantiationStrategy>per-lookupinstantiationStrategy>
      <executionStrategy>once-per-sessionexecutionStrategy>
      <threadSafe>falsethreadSafe>
      <parameters>
        <parameter>
          <name>projectname>
          <type>org.apache.maven.project.MavenProjecttype>
          <required>falserequired>
          <editable>trueeditable>
          <description>description>
        parameter>
      parameters>
      <configuration>
        <project implementation="org.apache.maven.project.MavenProject">${project}project>
      configuration>
    mojo>
  mojos>
  <dependencies>
    <dependency>
      <groupId>org.apache.maven.plugin-toolsgroupId>
      <artifactId>maven-plugin-annotationsartifactId>
      <type>jartype>
      <version>3.6.2version>
    dependency>
    <dependency>
      <groupId>org.apache.mavengroupId>
      <artifactId>maven-coreartifactId>
      <type>jartype>
      <version>3.3.9version>
    dependency>
    <dependency>
      <groupId>org.apache.mavengroupId>
      <artifactId>maven-modelartifactId>
      <type>jartype>
      <version>3.3.9version>
    dependency>
    <dependency>
      <groupId>org.apache.mavengroupId>
      <artifactId>maven-settingsartifactId>
      <type>jartype>
      <version>3.3.9version>
    dependency>
    <dependency>
      <groupId>org.apache.mavengroupId>
      <artifactId>maven-settings-builderartifactId>
      <type>jartype>
      <version>3.3.9version>
    dependency>
    <dependency>
      <groupId>org.apache.mavengroupId>
      <artifactId>maven-builder-supportartifactId>
      <type>jartype>
      <version>3.3.9version>
    dependency>
    <dependency>
      <groupId>org.apache.mavengroupId>
      <artifactId>maven-repository-metadataartifactId>
      <type>jartype>
      <version>3.3.9version>
    dependency>
    <dependency>
      <groupId>org.apache.mavengroupId>
      <artifactId>maven-artifactartifactId>
      <type>jartype>
      <version>3.3.9version>
    dependency>
    <dependency>
      <groupId>org.apache.mavengroupId>
      <artifactId>maven-plugin-apiartifactId>
      <type>jartype>
      <version>3.3.9version>
    dependency>
    <dependency>
      <groupId>org.apache.mavengroupId>
      <artifactId>maven-model-builderartifactId>
      <type>jartype>
      <version>3.3.9version>
    dependency>
    <dependency>
      <groupId>com.google.guavagroupId>
      <artifactId>guavaartifactId>
      <type>jartype>
      <version>18.0version>
    dependency>
    <dependency>
      <groupId>org.apache.mavengroupId>
      <artifactId>maven-aether-providerartifactId>
      <type>jartype>
      <version>3.3.9version>
    dependency>
    <dependency>
      <groupId>org.eclipse.aethergroupId>
      <artifactId>aether-spiartifactId>
      <type>jartype>
      <version>1.0.2.v20150114version>
    dependency>
    <dependency>
      <groupId>org.eclipse.aethergroupId>
      <artifactId>aether-implartifactId>
      <type>jartype>
      <version>1.0.2.v20150114version>
    dependency>
    <dependency>
      <groupId>org.eclipse.aethergroupId>
      <artifactId>aether-apiartifactId>
      <type>jartype>
      <version>1.0.2.v20150114version>
    dependency>
    <dependency>
      <groupId>org.eclipse.aethergroupId>
      <artifactId>aether-utilartifactId>
      <type>jartype>
      <version>1.0.2.v20150114version>
    dependency>
    <dependency>
      <groupId>org.eclipse.sisugroupId>
      <artifactId>org.eclipse.sisu.plexusartifactId>
      <type>jartype>
      <version>0.3.2version>
    dependency>
    <dependency>
      <groupId>javax.enterprisegroupId>
      <artifactId>cdi-apiartifactId>
      <type>jartype>
      <version>1.0version>
    dependency>
    <dependency>
      <groupId>javax.annotationgroupId>
      <artifactId>jsr250-apiartifactId>
      <type>jartype>
      <version>1.0version>
    dependency>
    <dependency>
      <groupId>org.eclipse.sisugroupId>
      <artifactId>org.eclipse.sisu.injectartifactId>
      <type>jartype>
      <version>0.3.2version>
    dependency>
    <dependency>
      <groupId>com.google.injectgroupId>
      <artifactId>guiceartifactId>
      <type>jartype>
      <version>4.0version>
    dependency>
    <dependency>
      <groupId>javax.injectgroupId>
      <artifactId>javax.injectartifactId>
      <type>jartype>
      <version>1version>
    dependency>
    <dependency>
      <groupId>aopalliancegroupId>
      <artifactId>aopallianceartifactId>
      <type>jartype>
      <version>1.0version>
    dependency>
    <dependency>
      <groupId>org.codehaus.plexusgroupId>
      <artifactId>plexus-interpolationartifactId>
      <type>jartype>
      <version>1.21version>
    dependency>
    <dependency>
      <groupId>org.codehaus.plexusgroupId>
      <artifactId>plexus-utilsartifactId>
      <type>jartype>
      <version>3.0.22version>
    dependency>
    <dependency>
      <groupId>org.codehaus.plexusgroupId>
      <artifactId>plexus-classworldsartifactId>
      <type>jartype>
      <version>2.5.2version>
    dependency>
    <dependency>
      <groupId>org.codehaus.plexusgroupId>
      <artifactId>plexus-component-annotationsartifactId>
      <type>jartype>
      <version>1.6version>
    dependency>
    <dependency>
      <groupId>org.sonatype.plexusgroupId>
      <artifactId>plexus-sec-dispatcherartifactId>
      <type>jartype>
      <version>1.3version>
    dependency>
    <dependency>
      <groupId>org.sonatype.plexusgroupId>
      <artifactId>plexus-cipherartifactId>
      <type>jartype>
      <version>1.4version>
    dependency>
    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-lang3artifactId>
      <type>jartype>
      <version>3.4version>
    dependency>
  dependencies>
plugin>

补充:  maven-core 自带的依赖maven-plugin-api, 所以文档模式也不需要单独再引入

查看依赖树如下:

$ mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building my-mvn-plugin 3.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ my-mvn-plugin ---
[INFO] cn.qz.cloud:my-mvn-plugin:maven-plugin:3.0-SNAPSHOT
[INFO] +- org.apache.maven.plugin-tools:maven-plugin-annotations:jar:3.6.2:compile
[INFO] \- org.apache.maven:maven-core:jar:3.3.9:compile
[INFO]    +- org.apache.maven:maven-model:jar:3.3.9:compile
[INFO]    +- org.apache.maven:maven-settings:jar:3.3.9:compile
[INFO]    +- org.apache.maven:maven-settings-builder:jar:3.3.9:compile
[INFO]    |  \- org.apache.maven:maven-builder-support:jar:3.3.9:compile
[INFO]    +- org.apache.maven:maven-repository-metadata:jar:3.3.9:compile
[INFO]    +- org.apache.maven:maven-artifact:jar:3.3.9:compile
[INFO]    +- org.apache.maven:maven-plugin-api:jar:3.3.9:compile
[INFO]    +- org.apache.maven:maven-model-builder:jar:3.3.9:compile
[INFO]    |  \- com.google.guava:guava:jar:18.0:compile
[INFO]    +- org.apache.maven:maven-aether-provider:jar:3.3.9:compile
[INFO]    |  \- org.eclipse.aether:aether-spi:jar:1.0.2.v20150114:compile
[INFO]    +- org.eclipse.aether:aether-impl:jar:1.0.2.v20150114:compile
[INFO]    +- org.eclipse.aether:aether-api:jar:1.0.2.v20150114:compile
[INFO]    +- org.eclipse.aether:aether-util:jar:1.0.2.v20150114:compile
[INFO]    +- org.eclipse.sisu:org.eclipse.sisu.plexus:jar:0.3.2:compile
[INFO]    |  +- javax.enterprise:cdi-api:jar:1.0:compile
[INFO]    |  |  \- javax.annotation:jsr250-api:jar:1.0:compile
[INFO]    |  \- org.eclipse.sisu:org.eclipse.sisu.inject:jar:0.3.2:compile
[INFO]    +- com.google.inject:guice:jar:no_aop:4.0:compile
[INFO]    |  +- javax.inject:javax.inject:jar:1:compile
[INFO]    |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO]    +- org.codehaus.plexus:plexus-interpolation:jar:1.21:compile
[INFO]    +- org.codehaus.plexus:plexus-utils:jar:3.0.22:compile
[INFO]    +- org.codehaus.plexus:plexus-classworlds:jar:2.5.2:compile
[INFO]    +- org.codehaus.plexus:plexus-component-annotations:jar:1.6:compile
[INFO]    +- org.sonatype.plexus:plexus-sec-dispatcher:jar:1.3:compile
[INFO]    |  \- org.sonatype.plexus:plexus-cipher:jar:1.4:compile
[INFO]    \- org.apache.commons:commons-lang3:jar:3.4:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.851 s
[INFO] Finished at: 2021-12-07T20:46:56+08:00
[INFO] Final Memory: 12M/241M
[INFO] ------------------------------------------------------------------------