From the beginning to the end, I'll teach you how to build Java projects with Maven

Keywords: Programming Maven Java Apache xml

This guide will guide you through building a simple Java project using Maven.

What will you build

You will create an application that provides the time of day, and then build it using Maven.

What do you need?

1. About 15 minutes
2. Favorite text editor or IDE
3. JDK 8 or later

How to complete this guide

You can start from scratch and complete each step, or you can bypass the basic setup steps that you are already familiar with. Either way, you can end up using working code.

Set up project

First, you need to set up a Java project for Maven to build. To focus on maven, now make the project as simple as possible. Create this structure in the project folder of your choice.

Create directory structure

In the project directory you selected, create the following subdirectory structure; for example, * * mkdir -p src/main/java/hello is on the * nix * * system:

Building Java projects with Maven

In the src/main/java/hello directory, you can create any Java class you need. To be consistent with the rest of this guide, create two classes: HelloWorld.java and Greeter.java.

src/main/java/hello/HelloWorld.java
.

package hello;
    
    public class HelloWorld {
        public static void main(String[] args) {
            Greeter greeter = new Greeter();
            System.out.println(greeter.sayHello());
        }
    }

src/main/java/hello/Greeter.java

package hello;
    
    public class Greeter {
        public String sayHello() {
            return "Hello world!";
        }
    }

 

Now that you are ready to build the project using maven, the next step is to install Maven.

Maven can be downloaded as a zip file from https://maven.apache.org/download.cgi. Only binaries are required, so look for a link to Apache Maven - {version} - bin.zip or Apache Maven - {version} - bin.tar.gz.

After downloading the zip file, extract it to your computer. Then add the bin folder to your path.

To test the Maven installation, run mvn from the command line:

mvn -v


If all goes well, you should be provided with some information about your Maven installation. It looks similar (though slightly different) to the following:

Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47+00:00)
    Maven home: /home/dsyer/Programs/apache-maven
    Java version: 1.8.0_152, vendor: Azul Systems, Inc.
    Java home: /home/dsyer/.sdkman/candidates/java/8u152-zulu/jre
    Default locale: en_GB, platform encoding: UTF-8
    OS name: "linux", version: "4.15.0-36-generic", arch: "amd64", family: "unix"

 

Congratulations! You now have Maven installed.

Information: you may want to consider using the [Maven wrapper]( https://github.com/takari/maven-wrapper )Enables developers to avoid having the right version of Maven or installing it completely. From [Spring Initializr]( https://start.spring.io/ )All downloaded items contain wrappers. It shows mvnw in the form of script at the top of the project instead of mvn.

Define a simple Maven build

Now that Maven is installed, you need to create a maven project definition. The Maven project is defined using an XML file called pom.xml. This file provides, among other things, the name of the project, its version, and its dependencies on external libraries.
Create a file named pom.xml in the root directory of the project (that is, place it next to the src folder) and provide the following:

pom.xml
.

<?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.springframework</groupId>
        <artifactId>gs-maven</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>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>hello.HelloWorld</mainClass>
                                                                </transformer>
                                                        </transformers>
                                                </configuration>
                                        </execution>
                                </executions>
                        </plugin>
                </plugins>
        </build>
</project>
Optional<packaging>Outside the element, this is the build Java The simplest pom.xml Papers. It includes details of the following project configuration:

  • <modelVersion>. POM Model Version (always 4.0.0).
  • <groupId>. The group or organization to which the project belongs. Usually represented as a reverse domain name.
  • <artifactId>. The name of the library artifact to assign to the project (for example, the name of its JAR or WAR file).
  • <version>. The version of the project being built.
  • <packaging>. How to package a project. For JAR file packaging, the default is "JAR". Use "WAR" to package WAR files.

So far, you have defined a minimal but powerful Maven project

Building Java code

Maven is now ready to build the project. You can now use Maven to perform several build lifecycle goals, including compiling project code, creating library packages (such as JAR files), and installing libraries in the local Maven dependency library.

To try to build, issue the following command on the command line:

mvn compile


This will run Maven and tell it to execute the compilation target. When you are finished, you should find the compiled. class file in the target / classes directory.

Because you are unlikely to want to distribute or use. class files directly, you may need to run the package target:

mvn package
The wrapper target compiles the Java code, runs any tests, and completes the target directory by packaging the code in an internal JAR file. The name of the JAR file will be based on the < artifactid > and < version > of the project. For example, given the previous minimum pom.xml file, the JAR file would be named gs-maven-0.1.0.jar.

To execute a JAR file, run:

java -jar target / gs-maven-0.1.0.jar

 


If you change the value < packaging > from "JAR" to "WAR", the result will be a WAR file in the target directory instead of a JAR file.

Maven also maintains a dependency repository on the local machine (usually in the. m2 / repository directory in the home directory) to quickly access project dependencies. If you want to install the JAR file of the project to the local repository, you should call the install target:

mvn  install

 


The code of the project will be compiled, tested and packaged at the installation target, then copied to the local dependency library, ready to be referenced as a dependency in another project.

When it comes to dependencies, it's time to declare them in the Maven build.

Declaration dependence
The simple Hello World example is completely independent and does not depend on any other libraries. However, most applications rely on external libraries to handle common and complex functions.

For example, suppose that in addition to saying "Hello World!" In addition, you want the application to print the current date and time. While you can use the date and time tools in the native Java library, you can use the Joda Time library to make things more interesting.

First, change HelloWorld.java as follows:

src/main/java/hello/HelloWorld.java
.

package hello;
    
    import org.joda.time.LocalTime;
    
    public class HelloWorld {
        public static void main(String[] args) {
            LocalTime currentTime = new LocalTime();
            System.out.println("The current local time is: " + currentTime);
            Greeter greeter = new Greeter();
            System.out.println(greeter.sayHello());
        }
    }
Here HelloWorld Use Joda Time Of LocalTime Class to get and print the current time.

If you are running mvn compile to build the project now, the build will fail because you have not declared Joda Time as a compilation dependency in the build. You can solve this problem by adding the following lines to pom.xml (within the < project > element):

<dependencies>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.2</version>
        </dependency>
</dependencies>
The XML block declares a list of dependencies for the project. Specifically, it declares a dependency for the Joda Time library. Within the < dependency > element, the dependency coordinates are defined by three child elements:

  • < groupid > - the group or organization to which the dependency belongs.
  • < artifactid > - required library.
  • < version > - a specific version of the library required.

By default, all dependencies are scoped as compile dependencies. That is, they should be available at compile time (if you are building a WAR file, included in the / WEB-INF / libs folder of the WAR). In addition, you can specify a < scope > element to specify one of the following ranges:

Provided - the dependencies required to compile the project code, but will be provided at run time by the container that runs the code, such as the Java Servlet API.
test - the dependency used to compile and run tests, but not required to build or run the runtime code for the project.
Now, if you run mvn compile or mvn package, Maven should resolve the Joda Time dependency from the Maven Central repository, and the build will succeed

Compiling test

First, add JUnit as a dependency on pom.xml in the scope of test:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
Then create a test case as follows:

src/test/java/hello/GreeterTest.java
.

package hello;
    
    import static org.hamcrest.CoreMatchers.containsString;
    import static org.junit.Assert.*;
    
    import org.junit.Test;
    
    public class GreeterTest {
    
        private Greeter greeter = new Greeter();

@Test
    public void greeterSaysHello() {
        assertThat(greeter.sayHello(), containsString("Hello"));
    }

}
Maven Use a name“ surefire"To run unit tests. The default configuration for this plug-in will be compiled and run src/test/java All classes with matching names*Test. You can run tests on the command line like this

mvn test

Or just use the steps shown above for mvn install (there is a lifecycle definition where "test" is included as a phase of "Install").

This is the completed pom.xml file:

<?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.springframework</groupId>
    <artifactId>gs-maven</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>

<dependencies>
        <!-- tag::joda[] -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- end::joda[] -->
        <!-- tag::junit[] -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- end::junit[] -->
    </dependencies>

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>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>hello.HelloWorld</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
Complete pom.xml File in use Maven Shade Plug in to JAR The file is executable. The focus of this guide is to get started Maven,Instead of using this specific plug-in.

abstract
Congratulations! You have created a simple and effective Maven project definition to build Java projects.

You can also have a look
The following guidelines may also help:

[build a Java project using Gradle]( https://blog.csdn.net/weixin_46577306/article/details/105515324)

Posted by rich11 on Tue, 14 Apr 2020 05:30:15 -0700