"Spring" building Java Projects with Maven__java

Source: Internet
Author: User
Tags local time mkdir git clone maven central maven shade plugin

Build Java Engineering with MAVEN


This guide will guide you through the use of MAVEN to build a simple Java project.


1, you will establish the project is what-what you'll build
You will first create an application that provides the time of day and then use MAVEN to build it.
2, what you will need-what you ll need

About 15 minutes A favorite text editor or IDE JDK6 above
3. How to complete this guide-how to complete this guide

Just like the Spring Starter guide, you can start from scratch and complete each step, or you can bypass the ones that are already familiar to you

Create a step. Either way, you have completed the work code.

Starting from scratch, go to "4, build the project".

To bypass the basic configuration, follow these steps:

Download and unzip the source code for this guide, or use the git command to copy: git clone https://github.com/spring-guides/gs-maven.git
Use the CD command to enter the directory gs-maven/initial jump to the head of [initial] when you're done, you can check your results against the code in Gs-maven/complete.

4, the establishment of the project-set up the project

First, you need to build a Java project for MAVEN. To stay focused on Maven, we are now trying to get engineering

The simpler the better. Create a directory structure

In your chosen engineering directory, create a subdirectory structure like the following;

Use Mkdir-p Src/main/java/hello under the *nix system:

(plus: Can be used under Windows: mkdir Src\main\java\hello)

└──SRC
    └──main
        └──java
            └──hello

In the Src/main/java/hello directory, you can create any class you want. To maintain consistency with the remainder of this guide,

The following two classes need to be created: 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!";
    }
}

So far, you have a project ready to be built by Maven, and the next step is to install MAVEN.

Maven in Link: http://maven.apache.org/download.cgi as a zip file can be downloaded. Only one of the binary

Files are needed, so find Apache-maven-{version}-bin.zip or apache-maven-{version}-bin.tar.gz

The link.

Once you have downloaded the zip file, unzip it to your computer. Then add the path of the bin folder to your computer

Path.

Let's test the success of MAVEN's installation and run the mvn command at the console command line:

(Note that when you modify the system variable path, you need to create a new console window to take effect, and the previously opened console window will not take effect.) )

Microsoft Windows XP [version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and settings\sine>mvn-v

error:java_home not found in your environment.
Please set the java_home variable in your environment to match the location of your
JAVA installation.

C:\Documents and Settings\sine>

The above hint indicates that the JAVA_HOME variable is not set in the system variable. Add Java_home to the system variable whose value is the JDK's

Installation path: For example, C:\Program files\java\jdk1.7.0_60

Reopen a console command line, run Mvn-v or mvn-version, and display the following:

C:\Documents and Settings\sine>mvn-v
Apache Maven 3.2.3 (33F8C3E1027C3DDDE99D3CDEBAD2656A31E8FDF4; 2014-08-12t04:58:10+08:00)
Maven home:d:\java\spring\apache-maven\apache-maven-3.2.3\bin\.
Java version:1.7.0_60, vendor:oracle Corporation
java home:c:\program files\java\jdk1.7.0_60\jre
Default LOCALE:ZH_CN, platform ENCODING:GBK
OS Name: "Windows XP", Version: "5.1", Arch: "x86", Family: "Windows"

Now, congratulations on your successful installation of MAVEN. More MAVEN configuration instructions please refer to: Apache maven Installation Instructions


5. Define a simple Maven builder-define a plain maven build


After MAVEN has been successfully installed, you need to create a MAVEN project definition. MAVEN is defined as an XML file named Pom.xml.

Among other things, this XML file gives the name of the project, its version, and its dependencies on the external library files.

Create an XML file under the root of the project named: Pom.xml, which reads as follows:

<?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 http:// Maven.apache.org/maven-v4_0_0.xsd "> <modelVersion>4.0.0</modelVersion> <groupId> Org.springframework</groupid> <artifactId>gs-maven</artifactId> <packaging>jar</ packaging> <version>0.1.0</version> <build> <plugins> &LT;PLUGIN&G
                T <groupId>org.apache.maven.plugins</groupId> <artifactid>maven-shade-plugin</artifacti d> <version>2.1</version> <executions> <execut
                            Ion> <phase>package</phase> <goals>
         <goal>shade</goal>               </goals> <configuration> &LT;TRANSFORMERS&G
                                T <transformer implementation= "Org.apache.maven.plugins.shade.resource.ManifestResour Cetransformer "> <mainclass>hello. Helloworld</mainclass> </transformer> &LT;/TRANSFO rmers> </configuration> </execution> </execu tions> </plugin> </plugins> </build> </project>

In addition to the <packaging> element is optional, create a Java engineering necessary XML configuration, this for the Pom.xml file is

The simplest possible. It contains the following engineering configuration information:

<modelVersion> Pom model version (always 4.0.0) <groupId>-the group or organization to which the project belongs. Typically represented as an inverted domain name. <artifactId>-the name of the library file for the project (for example, its jar or the name of the war file) <version>-the version of the currently constructed project. <packaging>-How the project should be packaged. By default, "Jar" is packaged as a jar file, and "war" is packaged as a war file. Note: When it comes to choosing a versioning scheme, Spring recommends the [Semantic versioning] (http://semver.org) approach.

Here, you have a minimal, maven-capable engineering definition.


6. Building Java code-build Java codes

MAVEN is ready to build the project. You can use Maven to perform several goals for building a lifecycle, including these goals:

Compile the project code, create a library file package (for example, a jar file), and install the library file into the local Maven dependency library.

To try to build the project, the command line executes the following command: (the directory executing the command is the root of the project)

MVN Compile

This will run Maven and tell it to perform the compilation. When the compilation is complete, you will find the compilation in the Target/classes directory

The. class file that was generated.

You may not want to publish or work directly with a. class file, and at this point you probably want to run package:

MVN Package

After the package command runs, it compiles your Java code, runs all the tests, and finally packs the code into a jar file to

To end in the target directory. The name of the jar file here is based on engineering <artifactId> and <version>.

For example, the smallest pom.xml given before it generates a jar file will be named Gs-maven-0.1.0.jar.


Note: If you ' ve changed the value of <packaging> from ' jars ' to ' war ', the result

Would be a WAR file within the target directory instead of a JAR file.


For quick access to project dependencies, Maven maintains a dependency library on your local machine (usually in

A. M2/repository directory in your home directory.

If you want to install your project's jar file into the local library, you need to invoke the install command:

MVN Install

After executing the install command, you will compile, test, and package your project code, then copy it to the local dependency library.

Prepare for additional projects to its dependence.

Now that we're talking about dependencies, it's time to introduce how to declare dependencies in a MAVEN build.


7. Declaration Dependency-declare Dependencies


The simple HelloWorld sample is fully self-contained and does not rely on any additional library files. However, most applications

is relying on external library files to handle common or complex functions.

For example, suppose that apart from printing "Hello world". "Outside, you also want the application to print the current date and time. Of course

Here you can use the local Java library file to bring the date time class, but you can make things more interesting, we use here

Joda Time library file.

First, modify the Helloworld.java file in the following ways:

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 uses the Joda time LocalTime class to get and print the current times.

If you use MVN compile to build your project at this point, you will fail. The reason for the failure is that there is no build in the file

Joda time is declared as a compilation dependency in. You can add the following lines to the Pom.xml (within <project> elements):

<dependencies>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactid >joda-time</artifactId>
            <version>2.2</version>
        </dependency>
    </ Dependencies>

This XML module declares the list of dependent libraries that the project requires. In particular, this only declares a dependency for the Joda Time library.

Within the <dependency> element, this dependent coordinate is defined by 3 child elements:

<groupId>-the group or organization the dependency belongs to. <artifactId>-the library is required. <version>-The specific version of the library is required.
By default, all dependencies are examined as compilation dependencies. That is, they should be available at compile time (and if you are building a war file that contains the war under the/web-inf/libs file). In addition, you may specify a <scope> element to specify one of the following ranges: provided -dependencies that are required for compiling the project code, But that'll be provided at runtime by a container running the code (e.g., the Java Servlet API). Test -dependencies that are used for compiling and running tests, but not required for building or Running the project ' s runtime code.
Now if you run MVN compile or mvn package,maven should resolve Joda time dependencies from the MAVEN Central Library, and the build will be successful.

The complete Pom.xml file is provided here as follows:

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 http:// Maven.apache.org/maven-v4_0_0.xsd "> <modelVersion>4.0.0</modelVersion> <groupId> Org.springframework</groupid> <artifactId>gs-maven</artifactId> <packaging>jar</ Packaging> <version>0.1.0</version> <!--tag::joda[]--> <dependencies> &L T;dependency> <groupId>joda-time</groupId> <artifactid>joda-time</artifact id> <version>2.2</version> </dependency> </dependencies> <!--en D::joda[]--> <build> <plugins> <plugin> <groupid>org. Apache.maven.plugins</groupid> <artifactid>maven-shade-plugin</artifactid> <version>2.1</version> &LT;EXECUTIONS&G
                    T
                            <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <con
                                    Figuration> <transformers> <transformer
                                    implementation= "Org.apache.maven.plugins.shade.resource.ManifestResourceTransformer" > <mainclass>hello. Helloworld</mainclass> </transformer> &LT;/TRANSFO rmers> </configuration> </execution> </execu Tions> </plugin> </plugins> </build> </project> 

Note: The completed Pom.xml file is using the "Maven shade Plugin for the" simple

Convenience of making the JAR file executable. The focus of this guide is getting

Started with Maven, the not using this particular plugin.


8. Summary-summary


Congratulations to you. You have created a simple and effective MAVEN engineering definition for Java engineering.


Original link: https://spring.io/guides/gs/maven/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.