Combined with Maven to build Java project

The opening words

The guide will guide you to use Maven to build simple Java project.
 

Your application will be created

You'll build a simple application by means of Maven.
 

Tools you will need

  • Probably about 15 minutes;
  • Your favorite text editor or integrated development environment (IDE)
  • JDK 8 or later;
     

How to complete this guide

Like most of Spring Getting Started Like, you can start from scratch and complete each step, you can bypass you are already familiar with the basic setup steps. Such as which way on the code you can finally have a job.

  • To start from scratch, venue to set up the project ;
  • To skip foundation, do the following:
    • Download and unzip the guide will use the source code , or by Git to clone its operations:git clone https://github.com/spring-guides/gs-maven.git
    • Switch to gs-maven/initialthe directory;
    • Jump to the guidelines install Maven .

After everything is ready, you can check gs-maven/completethe code directory.
 

Setting project

First, set a Java project to Maven. In order to focus on Maven, to make the project as simple as possible.

Create a directory structure

In selecting the project directory, create the following directory structure from; for example, on Linux systems mkdir -p src/main/java/hello:

└── src
    └── main
        └── java
            └── hello

In the src/main/java/hellocatalog, we can create Java classes. For simplicity and consistency with the rest of the guide, Spring recommends creating two classes: HelloWorld.javaand 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!";
  }
}

 

Installing Maven

Now we have can use Maven to build the project, we begin to install Maven.

We can from https://maven.apache.org/download.cgi to get. Only the binaries, so look-maven-Apache {Version} -bin.zip maven-or-Apache {Version} -bin.tar.gz corresponding link.

Unzip the file, and add the bin directory to environment variable.

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

mvn -v

If all goes well, we'll see the following message:

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"

We have now installed a Maven.

Tip : We may consider using Maven Wrapper to ensure Maven version between developers for the same. From Spring Initializr downloaded items are included wrapper. It is now under a path in mvnwthe script to replace the mvncommand.

 

Define a simple Maven build

Now that you've installed Maven, we need to create a Maven project definition. Maven project is to use the name pom.xml XML file to be defined. In addition to other information, the document also provides project name, version, and dependencies on external libraries.

Create a file named in the root directory of the project pom.xml files (ie srccatalog next), which reads:

<?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>

In addition to the optional <packaging>external element, which is required to build the most simple Java project pom.xml file. It contains configuration information for the following items:

  • <modelVersion>: POM model version (always 4.0.0);
  • <groupId>: Group or organization project belongs. Usually expressed as reverse domain name;
  • <artifactId>: The name of the library to be imparted to the work item (e.g., the name of its JAR or WAR file);
  • <version>: Versions are building projects;
  • <packaging>: How to package the project. Using the "jar" to packaged as JAR, which is the default option. The use of "war" come packaged in a WAR file.

In the choice of version control scheme, Spring recommends using semantic version control method.

So far, we have defined a minimal but powerful Maven project.

 

Construction of Java code

Maven is now ready to build the project. We can now use Maven build lifecycle to perform several goals, including compiling the project code, create a library package (for example, JAR files) will be installed and will depend on the library to the local Maven repository.

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

mvn compile

This will run Maven, tell it to compile target. Upon completion, we should target / classes found in the directory compiled .class files.

Since we generally do not use direct distribution or .class files, so we may need to run the package targets:

mvn package

Java compiler package will target the younger brother of Armagh, run any test, the final code will be packaged into JAR files in the target directory. JAR file name will be project-based <artifactIs>and <version>. For example, the smallest pom.xml file before that, the JAR file that will be named gs-maven-0.1.0.jar.

To perform a JAR file, run:

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

If we <packaging>value from the "jar" was changed to "war", and that the result will be a WAR file in the destination directory, and not a JAR file.

Maven also maintains a local machine relies warehouse (usually in the home directory .m2 / repository directory), rely on quick access to the project. If you want to install the project's JAR file to the local repository, you should call installgoals:

mvn install

install target will compile, test, and packaging project code, then copy it to rely on local warehouse, for another project, which is incorporated in dependency.

Speaking of dependence, it is time to declare the dependency in Maven build in the.
 

Declare dependencies

The Hello World example is completely dependent, without any dependence. Two most applications rely on third-party library to handle common and / or complex functions realized.

For example, suppose that in addition to output "Hello World!", We hope that the application can print the current date. We can use Java library that comes with the Date and Time tool, you can use Joda Time library to make things more interesting.

First, HelloWorld.java changed:

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, HelloWorldby means of Joda Time of LocalTimeclass to get and print the current time.

If we now run mvn compileto build the project, to build will fail because we have not relied upon as a compile-time construct will Joda Time in a statement. We can add pom.xml file (in <poject>the inner element) to work around the problem:

<dependencies>
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>2.9.2</version>
		</dependency>
</dependencies>

The XML block and declares dependencies list of items. It declares dependencies for the Joda Time library. In the <dependencyinner element dependencies to collaborate consists of the following three elements:

  • <groupId>: Dependency group or organization belongs;
  • <artifactId>: Required libraries;
  • <version>: Specific version of the required library.

By default, all depend on the range are all compiledependent. They should be available (if we are to build a WAR file, including the WAR / WEB-INF / libs folder) at compile time. We can give <scope>the specified range following elements:

  • provided: Compiled code depends on the desired item, the container will be provided by the run code (e.g., Java Servlet API) at runtime;
  • test: For dependent compile and run tests, but for run-time code to build or run the project is not necessary.

Now, we run mvn compileor mvn packageif, Maven should be resolved Joda Time dependence from Maven repository and successfully build the project.

 

Write a test

First JUnit DEPENDENT added pom.xml Test scope:

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
	<scope>test</scope>
</dependency>

Then create a test case:
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 uses a plug-in called "surefire" to run the unit tests. The default configuration of the plug-in is to compile and run src/test/javain the name *Testmatches the class. We can run tests on the command line:

mvn test

Or just above it has been shown mvn installnot (yet another lifecycle definition, which "test" as the "install" a stage).

Here is the complete pom.xmlfile:
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>

	<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 uses Maven Shade plugin to make the JAR file of the executable. The focus of the guide is to learn to use Maven, instead of using the specific plug-ins.

 

Outline

Congratulations! We created a simple and effective Maven build file for building Java projects.
 

See also

The following guidelines may be helpful:

Want to see other content guidelines? Please visit this guide belongs to column: " the Spring Official Guide "

Published 77 original articles · won praise 6 · views 1593

Guess you like

Origin blog.csdn.net/stevenchen1989/article/details/104073927