Maven Tutorial - Maven Plugins








Maven is actually a plugin container.

Each task is done by a plugin.

We can use Maven Plugins to:

  • compile source code files
  • create jar file
  • create war file
  • run unit testing
  • create project documentation
  • create project reports




Syntax

We can use the following syntax to execute a plugin and its goal.

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

The following code uses maven-compiler-plugin's compile-goal to compile a Java project.

mvn compiler:compile

Plugin Types

Maven provided following two types of Plugins:

Type Description
Build plugins execute during the build and they should be configured in the <build/> element from the pom.xml file.
Reporting plugins execute during the site generation and they should be configured in the <reporting/> element from the pom.xml.

Common plugins

The following table lists a few of common plugins.

PluginDescription
cleanClean up after the build.
compiler
Compiles Java sources.
deployDeploy the built artifact to the remote repository.
failsafeRun the JUnit tests in an isolated classloader.
installCopy the built artifact into the local repository.
resourcesCopy the resources to the output directory for including in the JAR.
siteGenerate a site for the current project.
earGenerate an EAR from the current project.




Example

The following pom.xml file shows how to config executions to output text.

<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>com.java2s.project</groupId>
<artifactId>simpleCode</artifactId>
<version>1.0</version>
<build>
<plugins>
   <plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-antrun-plugin</artifactId>
   <version>1.1</version>
   <executions>
      <execution>
         <id>id.clean</id>
         <phase>clean</phase>
         <goals>
            <goal>run</goal>
         </goals>
         <configuration>
            <tasks>
               <echo>hi from plugin.</echo>
            </tasks>
         </configuration>
      </execution>     
   </executions>
   </plugin>
</plugins>
</build>
</project>

Save the code above to c:\mvn_test, open command console and go to c:\mvn_test execute the following mvn command.

C:\mvn_text>mvn clean