Saturday, February 5, 2022

Maven : An Introduction to Java Build

Maven Introduction

Updated : Feb 3, 2022



Maven is a free software utility, like unix makefile, to automate compiling, testing, and packaging Java source code. In simple terms, a bunch of Java source files is needed to make a program. Maven is a single command to compile all of those Java files into a program, test the program (using JUNIT), then package up the program (into JAR). To configure Maven, it  reads pom.xml to define targets, much like unix makefile; newer build tools like Gradle define tasks.

Hello World Example:

  •     Install Maven

 

%brew install maven # installs Maven on a Mac

%mvn –version # Apache Maven 3.6.3
 

%which mvn # /usr/local/bin/mvn



  •     Create a playground:


%cd /Users/chiangal/Learn/Maven/0Hello

#%cd /Users/chiangal/Learn/JavaFun/MavenHelloWorld

#%cd /Users/chiangal/Learn/Maven/Tmp

  •     Use Maven to create project scaffold


%mvn \

archetype:generate \

-DgroupId=com.vmbc.app \

-DartifactId=dapp-ecs \

-DarchetypeArtifactId=maven-archetype-quickstart \

-DarchetypeVersion=1.4 \

-DinteractiveMode=false

# will create dir dapps-ecs/, with pom.xml and src/

# src/main and src/test


  •  Go to Maven projects “dapps-ecs” directory


%cd dapps-ecs


  •     Look at pom.xml

%cat pom.xml

<project>

    <groupId> com.vmbc.app </groupId> # the company domain?

    <artifactId> dapps-ecs </artifactId> #name of app in build system world

    <version> 1.0-SNAPSHOT </version>

    <name> dapps-ecs </name> # name of app in English

    <dependencies>

…..       <artifactId>junit</artifactId>     # easy way to test Java

</dependencies>

    <build> <pluginManagement><plugin> #build contains plugins

          <artifactId>maven-compiler-plugin</artifactId>

          <version>3.8.0</version> # version of Maven

        </plugin>

    </build>

</project>


  •     Edit App.java to put in "Hello World"

 

%vi src/main/java/com/vmbc/app/App.java # HelloWorld.java



        public class App {

 public static void main() { #             Remember “PlayStation Very Manly”


         System.out.print("hi \n");

       }

public static int giveMeOne() {


           return 1;

  }


}

  •       Edit AppTest.java to test "giveMeOne()"

%vi src/main/java/com/vmbc/app/AppTest.java # HelloWorld.java

  •     Use Maven to test compile

%mvn compile     # [INFO] BUILD SUCCESS, create target/



  •     Use Maven to “package”, which means, compile->test->package into jar

%mvn package     #