Mojo: Maven plain Old Java Object
1、插件命名规则:maven-<yourplugin>-plugin是Maven的保留字段,不允许使用,我们可以用<myplugin>-maven-plugin来命名自己开发的插件。
2、自定义插件代码,注意pom文件的packaging类型是maven-plugin,否则无法识别为插件类型。
1 import org.apache.maven.plugin.AbstractMojo; 2 import org.apache.maven.plugin.MojoExecutionException; 3 import org.apache.maven.plugins.annotations.Mojo; 4 import org.apache.maven.plugins.annotations.Parameter; 5 6 /** 7 * 支持的命令: 8 * mvn com.sample.myplugin:hello-maven-plugin:1.0-SNAPSHOT:sayhi 9 * 默认输出Hello World! 10 * 当配置了<greeting>Welcome</greeting>,输出Welcome 11 * mvn com.sample.myplugin:hello-maven-plugin:1.0-SNAPSHOT:sayhi -Dsayhi.greeting=hello 12 * 未配置<greeting>Welcome</greeting>时输出hello 13 */ 14 @Mojo(name = "sayhi") 15 public class GreetingMojo extends AbstractMojo { 16 17 // 参数,可以用参数表达式${project.version} 18 // 不同的参数类型的pom配置也不同 19 @Parameter(property = "sayhi.greeting", defaultValue = "Hello World!") 20 private String greeting; 21 22 @Override 23 public void execute() throws 24 MojoExecutionException { 25 getLog().info(greeting); 26 } 27 }
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.sample.myplugin</groupId> 8 <artifactId>hello-maven-plugin</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>maven-plugin</packaging> 11 19 <dependencies> 20 <dependency> 21 <groupId>org.apache.maven</groupId> 22 <artifactId>maven-plugin-api</artifactId> 23 <version>3.0</version> 24 </dependency> 25 26 <!-- @Mojo注解的依赖包 --> 27 <dependency> 28 <groupId>org.apache.maven.plugin-tools</groupId> 29 <artifactId>maven-plugin-annotations</artifactId> 30 <version>3.4</version> 31 <scope>provided</scope> 32 </dependency> 33 </dependencies> 34 35 <build> 36 <plugins> 37 <plugin> 38 <!-- 使用自定义插件--> 39 <groupId>com.sample.myplugin</groupId> 40 <artifactId>hello-maven-plugin</artifactId> 41 <version>1.0-SNAPSHOT</version> 42 <configuration> 43 <!-- greeting 是 @Parameter注解的参数--> 44 <greeting>Welcome</greeting> 45 </configuration> 46 </plugin> 47 </plugins> 48 </build> 49 </project>