乐闻世界logo
搜索文章和话题

How do Maven plugins work? What are the commonly used Maven plugins?

2月18日 21:34

Maven Plugin is a core component of the Maven build system, used to execute specific build tasks. Each plugin contains one or more goals, and goals correspond to specific operations in the build process.

Basic Concepts of Plugins:

  • Plugin: A collection of related goals used to complete specific types of build tasks
  • Goal: A single task in a plugin that can be executed individually or bound to a lifecycle phase
  • Lifecycle Binding: Bind plugin goals to a phase of the Maven lifecycle for automatic execution

Common Plugins:

  1. maven-compiler-plugin: Compile Java source code
xml
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>11</source> <target>11</target> <encoding>UTF-8</encoding> </configuration> </plugin>
  1. maven-surefire-plugin: Run unit tests
xml
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0</version> <configuration> <skipTests>false</skipTests> <includes> <include>**/*Test.java</include> </includes> </configuration> </plugin>
  1. maven-jar-plugin: Package JAR files
xml
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.3.0</version> <configuration> <archive> <manifest> <mainClass>com.example.Main</mainClass> </manifest> </archive> </configuration> </plugin>
  1. maven-war-plugin: Package WAR files
  2. maven-resources-plugin: Process resource files
  3. maven-assembly-plugin: Create custom distribution packages
  4. spring-boot-maven-plugin: Spring Boot project packaging

Plugin Configuration Methods:

  1. Direct Configuration: Configure plugins directly in <build><plugins>
  2. Plugin Management: Uniformly manage plugin versions and configurations in <build><pluginManagement>

Binding Plugin Goals to Lifecycle:

xml
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>3.2.1</version> <executions> <execution> <id>attach-sources</id> <phase>verify</phase> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin>

Common Plugin Commands:

  • mvn plugin:goal: Execute a specific plugin goal, such as mvn compiler:compile
  • mvn help:describe -Dplugin=plugin-name: View detailed plugin information
  • mvn help:effective-pom: View effective POM configuration

Best Practices:

  • Use pluginManagement in parent POM to uniformly manage plugin versions
  • Reasonably configure plugin parameters to avoid unnecessary default behaviors
  • Use plugin binding to automate build processes
  • Regularly update plugin versions to get new features and fixes
  • For large projects, use profiles to distinguish plugin configurations for different environments
标签:Maven