Maven自定义插件以及使用

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

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

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

  官网建议插件名称的起名为<name>-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.0</modelVersion>

    <groupId>cn.qz.cloud</groupId>
    <artifactId>my-mvn-plugin</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <!--打包方式-->
    <packaging>maven-plugin</packaging>

    <dependencies>
        <!-- dependencies to annotations -->
        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>3.6.2</version>
            <optional>true</optional>
            <!-- annotations are not used at runtime because @Retention(value=CLASS), they are needed only to build the plugin -->
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>3.3.9</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>3.6.2</version>
            </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 = "<goal-name>" ) is the minimal required annotation.
 * @since <since-text>
 * @deprecated <deprecated-text>
 */
@Mojo( name = "<goal-name>",
        aggregator = <false|true>,
        configurator = "<role hint>",
        executionStrategy = "<once-per-session|always>", // (unsupported since Maven 3.0)
        inheritByDefault = <true|false>, // (unsupported since Maven 3.0)
        instantiationStrategy = InstantiationStrategy.<strategy>,
        defaultPhase = LifecyclePhase.<phase>,
        requiresDependencyResolution = ResolutionScope.<scope>,
        requiresDependencyCollection = ResolutionScope.<scope>, // (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 = "<goal-name>",
        phase = LifecyclePhase.<phase>,
        lifecycle = "<lifecycle-id>" )
public class MyMojo
        extends AbstractMojo
{
    /**
     * @since <since-text>
     * @deprecated <deprecated-text>
     */
    @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 <code>per-lookup</code> and <code>singleton</code> are supported)
     * @return the instantiation strategy
     */
    InstantiationStrategy instantiationStrategy() default InstantiationStrategy.PER_LOOKUP;

    /**
     * execution strategy: <code>once-per-session</code> or <code>always</code>.
     * @return <code>once-per-session</code> or <code>always</code>
     *
     * @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;
}
View Code

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.
 */

/**
 * <a href="/ref/3.0.4/maven-core/lifecycles.html">Lifecycle phases</a>.
 * @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;
    }

}
View Code

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

    @Parameter
    private List<String> 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.cloud</groupId>
                <artifactId>my-mvn-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>mvtest</goal>
                        </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.cloud</groupId>
                <artifactId>my-mvn-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>mvtest</goal>
                        </goals>
                        <!-- 传递参数 -->
                        <configuration>
                            <myAlias>
                                111222333444
                            </myAlias>
                            <multiParams>
                                <multiParam>11</multiParam>
                                <multiParam>22</multiParam>
                                <multiParam>33</multiParam>
                                <multiParam>44</multiParam>
                            </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======");
    }

}
View Code

7. 测试上面命令

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

            <plugin>
                <groupId>cn.qz.cloud</groupId>
                <artifactId>my-mvn-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

执行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

            <plugin>
                <groupId>cn.qz.cloud</groupId>
                <artifactId>my-mvn-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                            <goal>mvtest</goal>
                        </goals>
                        <!-- 传递参数 -->
                        <configuration>
                            <multiParams>
                                <multiParam>11</multiParam>
                                <multiParam>22</multiParam>
                                <multiParam>33</multiParam>
                                <multiParam>44</multiParam>
                            </multiParams>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

日志如下:

[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.0</modelVersion>

    <groupId>cn.qz.cloud</groupId>
    <artifactId>my-mvn-plugin</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <!--打包方式-->
    <packaging>maven-plugin</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>3.6.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>3.3.9</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>3.6.2</version>
            </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------------------------------");
    }

}
View Code

3. 打包后测试:

1. pom 增加

            <plugin>
                <groupId>cn.qz.cloud</groupId>
                <artifactId>my-mvn-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>print</goal>
                        </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<String> 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.0</modelVersion>

    <groupId>cn.qz.cloud</groupId>
    <artifactId>my-mvn-plugin</artifactId>
    <version>2.0-SNAPSHOT</version>

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

    <!--打包方式-->
    <packaging>maven-plugin</packaging>

    <dependencies>
        <!-- dependencies to annotations -->
        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>3.6.2</version>
            <optional>true</optional>
            <!-- annotations are not used at runtime because @Retention(value=CLASS), they are needed only to build the plugin -->
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>3.3.9</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>3.6.2</version>
                <configuration>
                    <!--设置插件执行的前缀-->
                    <goalPrefix>mp</goalPrefix>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2. 另一个项目

(1) pom引入插件

            <plugin>
                <groupId>cn.qz.cloud</groupId>
                <artifactId>my-mvn-plugin</artifactId>
                <version>2.0-SNAPSHOT</version>
            </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.cloud</groupId>
                <artifactId>my-mvn-plugin</artifactId>
                <version>2.0-SNAPSHOT</version>
                <executions>
                    <execution>
                        <!--如果不配置阶段默认走的是mojo 上的compile, 如果配置了就在该阶段走对应的goal-->
                        <goals>
                            <goal>mvtest</goal>
                        </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: ijЩ▒▒▒▒▒ļ▒ʹ▒û▒▒▒▒ѹ▒ʱ▒▒ 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: ijЩ▒▒▒▒▒ļ▒ʹ▒▒▒▒δ▒▒▒▒▒▒ȫ▒IJ▒▒▒▒▒
[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.cloud</groupId>
                <artifactId>my-mvn-plugin</artifactId>
                <version>2.0-SNAPSHOT</version>
                <executions>
                    <execution>
                        <!--如果不配置阶段默认走的是mojo 上的compile, 如果配置了就在该阶段走对应的goal-->
                        <phase>
                            clean
                        </phase>
                        <goals>
                            <goal>mvtest</goal>
                        </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: ijЩ▒▒▒▒▒ļ▒ʹ▒û▒▒▒▒ѹ▒ʱ▒▒ 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: ijЩ▒▒▒▒▒ļ▒ʹ▒▒▒▒δ▒▒▒▒▒▒ȫ▒IJ▒▒▒▒▒
[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"?>

<!-- Generated by maven-plugin-tools 3.6 -->

<plugin>
  <name>my-mvn-plugin</name>
  <description></description>
  <groupId>cn.qz.cloud</groupId>
  <artifactId>my-mvn-plugin</artifactId>
  <version>2.0-SNAPSHOT</version>
  <goalPrefix>mp</goalPrefix>
  <isolatedRealm>false</isolatedRealm>
  <inheritedByDefault>true</inheritedByDefault>
  <mojos>
    <mojo>
      <goal>generate</goal>
      <requiresDirectInvocation>false</requiresDirectInvocation>
      <requiresProject>true</requiresProject>
      <requiresReports>false</requiresReports>
      <aggregator>false</aggregator>
      <requiresOnline>false</requiresOnline>
      <inheritedByDefault>true</inheritedByDefault>
      <phase>package</phase>
      <implementation>cn.qz.GenarateProperties</implementation>
      <language>java</language>
      <instantiationStrategy>per-lookup</instantiationStrategy>
      <executionStrategy>once-per-session</executionStrategy>
      <threadSafe>false</threadSafe>
      <parameters>
        <parameter>
          <name>dateFormat</name>
          <type>java.lang.String</type>
          <required>false</required>
          <editable>true</editable>
          <description></description>
        </parameter>
        <parameter>
          <name>fileName</name>
          <type>java.lang.String</type>
          <required>false</required>
          <editable>true</editable>
          <description></description>
        </parameter>
        <parameter>
          <name>project</name>
          <type>org.apache.maven.project.MavenProject</type>
          <required>false</required>
          <editable>false</editable>
          <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>mvtest</goal>
      <requiresDirectInvocation>false</requiresDirectInvocation>
      <requiresProject>true</requiresProject>
      <requiresReports>false</requiresReports>
      <aggregator>false</aggregator>
      <requiresOnline>false</requiresOnline>
      <inheritedByDefault>true</inheritedByDefault>
      <phase>compile</phase>
      <implementation>cn.qz.MyMojo</implementation>
      <language>java</language>
      <instantiationStrategy>per-lookup</instantiationStrategy>
      <executionStrategy>once-per-session</executionStrategy>
      <threadSafe>false</threadSafe>
      <parameters>
        <parameter>
          <name>basedir</name>
          <type>java.io.File</type>
          <required>false</required>
          <editable>false</editable>
          <description></description>
        </parameter>
        <parameter>
          <name>mojo</name>
          <type>org.apache.maven.plugin.MojoExecution</type>
          <required>false</required>
          <editable>false</editable>
          <description></description>
        </parameter>
        <parameter>
          <name>multiParams</name>
          <type>java.util.List</type>
          <required>false</required>
          <editable>true</editable>
          <description></description>
        </parameter>
        <parameter>
          <name>parameter</name>
          <alias>myAlias</alias>
          <type>java.lang.String</type>
          <since>&lt;since-text&gt;</since>
          <deprecated>&lt;deprecated-text&gt;</deprecated>
          <required>true</required>
          <editable>false</editable>
          <description></description>
        </parameter>
        <parameter>
          <name>plugin</name>
          <type>org.apache.maven.plugin.descriptor.PluginDescriptor</type>
          <required>false</required>
          <editable>false</editable>
          <description></description>
        </parameter>
        <parameter>
          <name>project</name>
          <type>org.apache.maven.project.MavenProject</type>
          <required>false</required>
          <editable>false</editable>
          <description></description>
        </parameter>
        <parameter>
          <name>session</name>
          <type>org.apache.maven.execution.MavenSession</type>
          <required>false</required>
          <editable>false</editable>
          <description></description>
        </parameter>
        <parameter>
          <name>settings</name>
          <type>org.apache.maven.settings.Settings</type>
          <required>false</required>
          <editable>false</editable>
          <description></description>
        </parameter>
        <parameter>
          <name>target</name>
          <type>java.io.File</type>
          <required>false</required>
          <editable>false</editable>
          <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>print</goal>
      <description>使用文档的方式</description>
      <requiresDirectInvocation>false</requiresDirectInvocation>
      <requiresProject>true</requiresProject>
      <requiresReports>false</requiresReports>
      <aggregator>false</aggregator>
      <requiresOnline>false</requiresOnline>
      <inheritedByDefault>true</inheritedByDefault>
      <phase>initialize</phase>
      <implementation>cn.qz.PrintMojo</implementation>
      <language>java</language>
      <instantiationStrategy>per-lookup</instantiationStrategy>
      <executionStrategy>once-per-session</executionStrategy>
      <threadSafe>false</threadSafe>
      <parameters>
        <parameter>
          <name>project</name>
          <type>org.apache.maven.project.MavenProject</type>
          <required>false</required>
          <editable>true</editable>
          <description></description>
        </parameter>
      </parameters>
      <configuration>
        <project implementation="org.apache.maven.project.MavenProject">${project}</project>
      </configuration>
    </mojo>
  </mojos>
  <dependencies>
    <dependency>
      <groupId>org.apache.maven.plugin-tools</groupId>
      <artifactId>maven-plugin-annotations</artifactId>
      <type>jar</type>
      <version>3.6.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
      <type>jar</type>
      <version>3.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model</artifactId>
      <type>jar</type>
      <version>3.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-settings</artifactId>
      <type>jar</type>
      <version>3.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-settings-builder</artifactId>
      <type>jar</type>
      <version>3.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-builder-support</artifactId>
      <type>jar</type>
      <version>3.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-repository-metadata</artifactId>
      <type>jar</type>
      <version>3.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-artifact</artifactId>
      <type>jar</type>
      <version>3.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <type>jar</type>
      <version>3.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model-builder</artifactId>
      <type>jar</type>
      <version>3.3.9</version>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <type>jar</type>
      <version>18.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-aether-provider</artifactId>
      <type>jar</type>
      <version>3.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-spi</artifactId>
      <type>jar</type>
      <version>1.0.2.v20150114</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-impl</artifactId>
      <type>jar</type>
      <version>1.0.2.v20150114</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-api</artifactId>
      <type>jar</type>
      <version>1.0.2.v20150114</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-util</artifactId>
      <type>jar</type>
      <version>1.0.2.v20150114</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.sisu</groupId>
      <artifactId>org.eclipse.sisu.plexus</artifactId>
      <type>jar</type>
      <version>0.3.2</version>
    </dependency>
    <dependency>
      <groupId>javax.enterprise</groupId>
      <artifactId>cdi-api</artifactId>
      <type>jar</type>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>jsr250-api</artifactId>
      <type>jar</type>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.sisu</groupId>
      <artifactId>org.eclipse.sisu.inject</artifactId>
      <type>jar</type>
      <version>0.3.2</version>
    </dependency>
    <dependency>
      <groupId>com.google.inject</groupId>
      <artifactId>guice</artifactId>
      <type>jar</type>
      <version>4.0</version>
    </dependency>
    <dependency>
      <groupId>javax.inject</groupId>
      <artifactId>javax.inject</artifactId>
      <type>jar</type>
      <version>1</version>
    </dependency>
    <dependency>
      <groupId>aopalliance</groupId>
      <artifactId>aopalliance</artifactId>
      <type>jar</type>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-interpolation</artifactId>
      <type>jar</type>
      <version>1.21</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-utils</artifactId>
      <type>jar</type>
      <version>3.0.22</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-classworlds</artifactId>
      <type>jar</type>
      <version>2.5.2</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-component-annotations</artifactId>
      <type>jar</type>
      <version>1.6</version>
    </dependency>
    <dependency>
      <groupId>org.sonatype.plexus</groupId>
      <artifactId>plexus-sec-dispatcher</artifactId>
      <type>jar</type>
      <version>1.3</version>
    </dependency>
    <dependency>
      <groupId>org.sonatype.plexus</groupId>
      <artifactId>plexus-cipher</artifactId>
      <type>jar</type>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <type>jar</type>
      <version>3.4</version>
    </dependency>
  </dependencies>
</plugin>
View Code

补充:  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] ------------------------------------------------------------------------
【当你用心写完每一篇博客之后,你会发现它比你用代码实现功能更有成就感!】
原文地址:https://www.cnblogs.com/qlqwjy/p/15647590.html