Creating a Jar using Maven

In the earlier post, we had seen how to create a jar, in this post we will see how to create a jar using maven. Following are key points in creating the jar using maven.

1. Specify the packaging type e.g. jar.

2. Compile the source code. Use  maven-compiler-plugin here.

3. Generate eclipse related files like .classpath, etc. Use maven-eclipse-plugin. [optional]

4. Bundle the java class files in a jar. Use maven-jar-plugin.

5. Provide the main-class[entry point] for your jar in the mainfest.

6. Execute the unit-tests of your jar before creating the jar. [optional]

Refer to the sample pom.xml below:

<?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>com.schoudari.blog</groupId>
  <artifactId>my-blog-reader</artifactId>
  <packaging>jar</packaging> <!--1.Packaging Type -->
  <version>1.0.0-SNAPSHOT</version>
  <name>Blog Reader</name>

  <properties>   
    <log4j.version>1.2.16</log4j.version>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId> <!--2.Compiles the source-code -->
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId> <!--3.Generates the eclipse-related files -->
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId><!--4.Creates a jar -->
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <mainClass>com.schoudari.blog.BlogReader</mainClass><!--5.Add main class -->
            </manifest>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId><!--6.Executes the unit-test cases -->
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>       
  </dependencies>  
</project>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s