Maven 自定义插件实战

本文档详细介绍了如何使用IDEA创建一个Maven插件项目,包括配置pom.xml,定义Mojo,打包安装到本地仓库,并在另一个项目中引用和执行插件。通过一个具体的例子展示了自定义Maven插件的完整流程。
摘要由CSDN通过智能技术生成

实战

开发插件

使用 IDEA,创建一个org.apache.maven.archetypes:maven-archetype-mojo模版项目,项目名叫demo-maven-plugin
注意,maven 插件的命名有讲究的,官方插件命名格式是maven-pluginName-plugin,非官方插件的命名格式是pluginName-maven-plugin


修改 pom.xml 。

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>demo-maven-plugin</artifactId>
    <!--打包方式 maven-plugin-->
    <packaging>maven-plugin</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>demo Maven Mojo</name>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>3.6.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>3.6.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-plugin-plugin</artifactId>
                    <version>3.6.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

注意依赖的版本,尽量保持一致。


创建 Mojo。

/**
 * 执行插件的动作名称,命令是 mvn XXX:xxx
 */
@Mojo(name = "GetBlueBuff")
public class JungleMojo extends AbstractMojo {
    /**
     * 设置一个配置参数,默认值是 defaultValue 
     */
    @Parameter(name = "name", defaultValue = "韩信")
    private String name;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info(name + "在拿蓝");
    }
}


将插件打包安装到本地仓库。

$ mvn clean install

使用插件

创建另一个项目,引用我们创建的插件。

<?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">
    <parent>
        <artifactId>maven-plugin</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>sample</artifactId>

    <build>
        <plugins>
            <plugin>
                <groupId>org.example</groupId>
                <artifactId>demo-maven-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <configuration>
                    <name>李白</name>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

执行插件命令

$ mvn demo:KillDarknessKing
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------------< org.example:sample >-------------------------
[INFO] Building sample 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- demo-maven-plugin:1.0-SNAPSHOT:GetBlueBuff (default-cli) @ sample ---
[INFO] 李白在拿蓝
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.304 s
[INFO] Finished at: 2020-09-23T16:11:44+08:00
[INFO] ------------------------------------------------------------------------

Mojo 模版

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对应的目标的名称
@Mojo( name = "<goal-name>",
      aggregator = <false|true>, 
      configurator = "<role hint>",
      // 执行策略
      executionStrategy = "<once-per-session|always>",
      inheritByDefault = <true|false>,
      // 实例化策略
      instantiationStrategy = InstantiationStrategy.<strategy>,
      // 如果用户没有在POM中明确设置此Mojo绑定到的phase,那么绑定一个MojoExecution到那个phase
      defaultPhase = LifecyclePhase.<phase>,
      requiresDependencyResolution = ResolutionScope.<scope>,
      requiresDependencyCollection = ResolutionScope.<scope>,
      // 提示此Mojo需要被直接调用(而非绑定到生命周期阶段)
      requiresDirectInvocation = <false|true>,
      // 提示此Mojo不能在离线模式下运行
      requiresOnline = <false|true>,
      // 提示此Mojo必须在一个Maven项目内运行
      requiresProject = <true|false>,
      // 提示此Mojo是否线程安全,线程安全的Mojo支持在并行构建中被并发的调用
      threadSafe = <false|true> ) // (since Maven 3.0)

// 何时执行此Mojo
@Execute( goal = "<goal-name>",           // 如果提供goal,则隔离执行此Mojo
         phase = LifecyclePhase.<phase>, // 在此生命周期阶段自动执行此Mojo
         lifecycle = "<lifecycle-id>" )  // 在此生命周期中执行此Mojo
public class MyMojo
    extends AbstractMojo
{

    @Parameter( name = "parameter",
                // 在POM中可使用别名来配置参数
                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;


    @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 )
    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()
    {
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值