Skip to Content
Author's profile photo Jerry Wang

An example of building Java project using Maven

Prerequisite: download and configure Maven in your laptop. Once done, type “mvn” in command line and you should observe the following output by Maven:

/wp-content/uploads/2016/05/clipboard1_946331.png

Suppose I have a simple Java project with following package hierarchy:

/wp-content/uploads/2016/05/clipboard2_946332.png

The source code of MavenSandboxTest is also very simple:

package test.java.com.sap;
import static org.junit.Assert.assertEquals;
import main.java.com.sap.MavenSandbox;
import org.junit.Test;
public class MavenSandboxTest {
@Test
public void test() {
  MavenSandbox tool = new MavenSandbox();
  assertEquals(tool.hello(),"Hello world");
}
}

How to build this simple Java project using Maven?

Create a pom.xml under the root folder of your project,

/wp-content/uploads/2016/05/clipboard3_946333.png

and paste the following source code:

<?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.0http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
   <modelVersion>4.0.0</modelVersion> 
   <groupId>com.sap.MavenSandbox</groupId> 
   <artifactId>MavenSandbox</artifactId> 
   <version>0.0.1-SNAPSHOT</version> 
   <dependencies> 
          <dependency> 
               <groupId>junit</groupId> 
               <artifactId>junit</artifactId> 
               <version>4.10</version> 
               <scope>test</scope> 
          </dependency> 
   </dependencies> 
</project> 

Create a new Configuration:

/wp-content/uploads/2016/05/clipboard4_946335.png

Specify the following settings and click run:

/wp-content/uploads/2016/05/clipboard5_946336.png

If everything goes well, you should see the Build Success message:

/wp-content/uploads/2016/05/clipboard6_946337.png

and there will be a new folder “target” generated automatically:

/wp-content/uploads/2016/05/clipboard7_946338.png

go to folder classes, and you can execute the compiled java class via command “java main.java.com.sap.MavenSandbox“:

/wp-content/uploads/2016/05/clipboard8_946339.png

or you can also directly execute the jar file via the command below ( you should first navigate back to target folder )

/wp-content/uploads/2016/05/clipboard9_946340.png

since we have specified the dependency of JUnit with version 4.10 in pom.xml:

/wp-content/uploads/2016/05/clipboard10_946341.png

so when “mvn clean install” is executed, you can observe the corresponding jar file is automatically downloaded by Maven:

/wp-content/uploads/2016/05/clipboard11_946342.png

Finally you could find the downloaded jar file from this folder:

/wp-content/uploads/2016/05/clipboard12_946343.png

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.