How Do You Build a Java Program with Maven?

Problem scenario
You want to use Maven to build a Java program from source code. The code is in at least two different .java files. How do you run Maven to compile a .java file?

Solution
Prerequisites
This assumes that you have installed Maven. If you need assistance, see this posting.

Procedures
1. Run this command: mkdir -p src/main/java/contint
2. Create this file: src/main/java/contint/Helloer.java

package contint;

public class Helloer {
    public static void main(String[] args) {
        ContInt helloer = new ContInt();
        System.out.println(helloer.produceMessage());
    }
}

3. Create this file: src/main/java/contint/ContInt.java

package contint;

public class ContInt {
    public String produceMessage() {
        return "This program was written by Continual Integration";
    }
}

4. Create this pom.xml file with the following content

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.continualintegration</groupId>
    <artifactId>contint</artifactId>
    <packaging>jar</packaging>
    <version>0.1.0</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>contint.Helloer</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

5. Run these commands:

mvn compile
mvn package
java -jar target/contint-0.1.0.jar

Leave a comment

Your email address will not be published. Required fields are marked *