Maven创建第一个java项目(官方教程)
翻譯自:鏈接
Building Java Projects with Maven
This guide walks you through using Maven to build a simple Java
project.
使用Maven構建一個java項目?
這個指南使你通過使用Maven去創建一個簡單的Java項目
What you’ll build
You’ll create an application that provides the time of day and then
build it with Maven.
你將要創建什么?
你將提供今天的時間,然后通過Maven去,創建一個應用程序
What you’ll need(你需要的東西)
About 15 minutes(大概15分鐘)
A favorite text editor or IDE(一個喜歡的編輯器或者IDE(集成開發環境))
JDK 6 or later(JDK 6 或者更高的版本)
.
How to complete this guide
Like most Spring Getting Started guides,
you can start from scratch and complete each step, or you can bypass
basic setup steps that are already familiar to you. Either way, you
end up with working code.
如何完成這個指南?
像大部分Spring指南一樣,你可以從頭開始或者,完成每個部分,或者你可以繞開基本的設置步驟如果你已經很熟悉。不管怎樣,你最終都需要進行編碼工作
To start from scratch, move on to Set up the project.
To skip the basics, do the following:
1.Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-maven.git
2.cd into gs-maven/initial
3. Jump ahead to [initial].
從頭開始,跳轉到 建立項目。
跳過基本步驟,按照下面步驟:
1.下載或者從這個指南的字眼倉庫中解壓,或者克隆它使用
Git:git clone https://github.com/spring-guides/gs-maven.git
2.進去該目錄,執行
gs-maven/instial
3.向前跳轉去initial(項目名)
When you’re finished, you can check your results against the code in gs-maven/complete.
當你完成時,你可以選擇你的結果通過 gs-maven/complete
Set up the project
First you’ll need to setup a Java project for Maven to build. To keep the focus on Maven, make the project as simple as possible for now.
建立項目
首先你將需要去通過Maven構建一個java項目,使得焦點在Maven上,使項目像現在一樣簡單。
Create the directory structure
In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/java/hello on *nix systems:
創建一個目錄結構
在逆選擇的項目目錄中,創建下面子目錄結構;
例如 使用 mkdir -p src/main/java/hello(在*nix系統中)
Within the src/main/java/hello directory, you can create any Java classes you want. To maintain consistency with the rest of this guide, create these two classes: HelloWorld.java and Greeter.java.
在”src/main/java/hello” 目錄中,你可以創建任何你想要的java的類文件,最好和下面的指南一致,創建那兩個類文件,HelloWorld.java 和 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 have a project that is ready to be built with Maven, the next step is to install Maven.
Maven is downloadable as a zip file at http://maven.apache.org/download.cgi. Only the binaries are required, so look for the link to apache-maven-{version}-bin.zip or apache-maven-{version}-bin.tar.gz.
Once you have downloaded the zip file, unzip it to your computer. Then add the bin folder to your path.
現在你有一個通過Maven構建好的項目,先一步是 install(maven的一個命令) Maven
Maven是可以在這個網站下載zip版,http://maven.apache.org/download.cgi. 下載,只有這個文件是必須的。所以 查找這個鏈接,下載apache-maven-{version}-bin.zip(windows版本) or apache-maven-{version}-bin.tar.gz(linux版本)
你已經下載zip文件,把它解壓到你的計算機。然后添加 bin 目錄,到你的環境變量中。
To test the Maven installation, run mvn from the command-line:
測試maven安裝,在命令行中運行:mvn
mvn -vIf all goes well, you should be presented with some information about the Maven installation. It will look similar to (although perhaps slightly different from) the following:
如果一切都順利,你可以看到一些關于Maven安裝的信息,它看起來和下面的很像(盡管有一些細微的區別)
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 07:51:28-0600) Maven home: /usr/share/maven Java version: 1.7.0_09, vendor: Oracle Corporation Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre Default locale: en_US, platform encoding: UTF-8 OS name: "mac os x", version: "10.8.3", arch: "x86_64", family: "mac"Congratulations! You now have Maven installed.
祝賀你你現在可以運行Maven install
Define a simple Maven build
Now that Maven is installed, you need to create a Maven project definition. Maven projects are defined with an XML file named pom.xml. Among other things, this file gives the project’s name, version, and dependencies that it has on external libraries.
定義一個簡單的Maven build
現在這個Maven被 install ,你需要去創建一個 Maven項目定義。Maven項目是被通過名叫pom。xml的xml文件定義的。在其他事情中,這個文件,提供項目的名稱,版本,他已經繼承庫的依賴性
Create a file named pom.xml at the root of the project and give it the following contents:
在項目的根目錄下,創建一個文件名叫pom.xml,并提供下面內容
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><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>With the exception of the optional packaging> element, this is the simplest possible pom.xml file necessary to build a Java project. It includes the following details of the project configuration:
使用可選擇的packaging>標簽之外的,這個最簡單的 pom.xml 文件需要構建一個java項目。它導入下面的項目配置的細節
modelVersion pom 模型的版本 (總是 4.0.0).
groupId 項目所屬的團隊,通常表示成反寫的域名
artifactId 用于區分庫中項目的名稱(例如,jar或者war文件的名字)
version 項目構建的版本
packaging 項目如何被打包. 默認為jar,打包成jar文件. 使用war可以打包成war文件
When it comes to choosing a versioning scheme, Spring recommends the semantic versioning approach.
當談到選擇版本時,Spring 推薦使用[語義版本](http://semver.org/lang/zh-CN/ )方法
At this point you have a minimal, yet capable Maven project defined.
在這你制定一個最低的,但是也可以使用Maven項目默認的。
.
Build Java code
Maven is now ready to build the project. You can execute several build lifecycle goals with Maven now, including goals to compile the project’s code, create a library package (such as a JAR file), and install the library in the local Maven dependency repository.
To try out the build, issue the following at the command line:
構建java代碼
Maven 現在已經構建好了項目,你現在需要執行一些構建生命周期目標使用Maven,導入目標,去編譯項目的代碼,創建一個庫包(例如 一個 jar文件),并且,安裝lib在本地的Maven依賴倉庫中。
嘗試 去構建,在命令行中,發出下面在這條命令
This will run Maven, telling it to execute the compile goal. When it’s finished, you should find the compiled .class files in the target/classes directory.
Since it’s unlikely that you’ll want to distribute or work with .class files directly, you’ll probably want to run the package goal instead:
這將會運行Maven,告訴他,執行編譯目標。當他完成時,你可以找到編譯后的class文件,在target/classes 目錄中
你想發布或者和class文件一樣是不可能的,你大概需要運行,package 目標代替
mvn packageThe package goal will compile your Java code, run any tests, and finish by packaging the code up in a JAR file within the target directory. The name of the JAR file will be based on the project’s artifactId and version. For example, given the minimal pom.xml file from before, the JAR file will be named gs-maven-0.1.0.jar.
這個打包目標將會編譯你的java代碼,運行所有的測試文件,并且完成后將代碼打包成jar文件 放入 target 目錄中,jar文件的餅子是以項目的artifactId> 和 version>為基準的
例如,大抱歉提供一個最低版本的pom.xml文件,jar文件將會命名為 gs-maven-0.1.0.jar
If you’ve changed the value of packaging> from “jar” to “war”, the result will be a WAR file within the target directory instead of a JAR file.
如果你把packaging>標簽的值從jar改成war,結果將會是war文件,在target 目錄而不是一個jar文件,
Maven also maintains a repository of dependencies on your local machine (usually in a .m2/repository directory in your home directory) for quick access to project dependencies. If you’d like to install your project’s JAR file to that local repository, then you should invoke the install goal:
Maven也維護一個在你的本機的依賴倉庫(通常在 你的home目錄下的 .m2/repository 目錄),目的是快讀存取項目的依賴。如果你install你的項目jar文件到這個本地倉庫,然后,你需要調用 install 目標
mvn installThe install goal will compile, test, and package your project’s code and then copy it into the local dependency repository, ready for another project to reference it as a dependency.
Speaking of dependencies, now it’s time to declare dependencies in the Maven build.
這個install 命令 將會會執行,compile,test和package 對你的項目源碼,并且拷貝它到本地依賴倉庫,準備作為一個依賴給其他項目參考它
說到依賴,現在說說在Maven構建時,定時聲明依賴
Declare Dependencies
The simple Hello World sample is completely self-contained and does not depend on any additional libraries. Most applications, however, depend on external libraries to handle common and complex functionality.
For example, suppose that in addition to saying “Hello World!”, you want the application to print the current date and time. While you could use the date and time facilities in the native Java libraries, you can make things more interesting by using the Joda Time libraries.
First, change HelloWorld.java to look like this:
聲明依賴
一個簡單的HelloWorld是一個完全獨立并且沒有依賴的附加庫。然而,更多的應用程序依賴外部庫區使用共同的或者復雜的函數。
例如,假如除此之外 saying “Hello World”,你想應用程序打印當前數去和時間。當你像在本地java庫中使用數據和時間工具,你可以做一些更多有趣的事情通過使用 Joda Time 庫
首先,改變HelloWorld.java 看這個
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 Joda Time’s LocalTime class to get and print the current time.
If you were to run mvn compile to build the project now, the build would fail because you’ve not declared Joda Time as a compile dependency in the build. You can fix that by adding the following lines to pom.xml (within the project element):
這HelloWorld 使用 JodaTime的LocalTime類去獲取并打印當前的時間,
如果你運行 mvn compile 去構建這個項目,構建將會失敗,因為在構建時,你還沒有聲明 Joda Time 作為編譯的依賴。你可以將下面這幾行添加到pom.xml文件中(在project標簽中)
<dependencies><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.2</version></dependency> </dependencies>This block of XML declares a list of dependencies for the project. Specifically, it declares a single dependency for the Joda Time library. Within the dependency element, the dependency coordinates are defined by three sub-elements:
groupId - The group or organization that the dependency belongs to.
artifactId - The library that is required.
version - The specific version of the library that is required.
By default, all dependencies are scoped as compile dependencies. That is, they should be available at compile-time (and if you were building a WAR file, including in the /WEB-INF/libs folder of the WAR). Additionally, you may specify a scope> element to specify one of the following scopes:
provided - Dependencies that are required for compiling the project code, but that will 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 the Joda Time dependency from the Maven Central repository and the build will be successful.
這塊xml給項目聲明了一組依賴。特別強調,他聲明了一個單一的依賴,Joda Time庫。在dependency>標簽中,依賴坐標被定義通過三個標準標簽。
groupId> - 依賴所屬的組織或組
artifactId> - 這個是必須的,標志庫
version> - 這個是必須的,庫的版本
默認是,所有的依賴都會被作為編譯的依賴。他們應該被提供作為編譯時(如果 你構建一個war文件,導入war到/WEB-INF/libs 文件)。除此之外,你需要制定一個scope>標簽,去指定一個下面的范圍
provided - 依賴項目編譯所需的代碼,但這將在運行時通過提供一個容器運行代碼(比如java Servlet 的API).
test - 依賴項用于編譯和運行測試,但不是必需的建設或運行項目的運行時代碼。
如果你運行mvn編譯或者mvn包,Maven應該解決Joda Time依賴從Maven中央存儲庫和構建會成功。
Write a Test
First add JUnit as a dependency to your pom.xml, in the test scope:
首先添加JUnit pom作為依賴項。xml,在測試范圍:
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency>Then create a test case like this:
然后創建一個 測試 文件,想這個
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();@Testpublic void greeterSaysHello() {assertThat(greeter.sayHello(), containsString("Hello"));}}Maven uses a plugin called “surefire” to run unit tests. The default configuration of this plugin compiles and runs all classes in src/test/java with a name matching *Test. You can run the tests on the command line like this
Maven使用一個插件稱為“surefire”運行單元測試。這個插件的默認配置編譯和運行所有類在src/test/javawith名稱匹配*Test。您可以在命令行上運行測試
mvn testor just use mvn install step as we already showed above (there is a lifecycle definition where “test” is included as a stage in “install”).
Here’s the completed pom.xml file:
或者只是使用mvn install步驟如上我們已經顯示(有一個生命周期定義在“test”是包含在“install”階段)。
這是 完整的 pom.xml 文件
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><dependencies><!-- tag::joda[] --><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.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>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, not using this particular plugin.
完整的pom.xml 文件可以Maven shade 插件簡單鋼鞭的構建可執行的jar文件。這個指南的重點是開始使用Maven,這個特定的例子不使用這個插件
Summary
Congratulations! You’ve created a simple yet effective Maven project definition for building Java projects.
Want to write a new guide or contribute to an existing one? Check out our contribution guidelines.
總結
恭喜你!您已經創建了一個簡單但有效的Maven項目定義構建Java項目。
想寫一個新的指南或導致現有的嗎?看看我們貢獻的指導方針。
總結
以上是生活随笔為你收集整理的Maven创建第一个java项目(官方教程)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用libpcap分析CAIDA的网络流量
- 下一篇: 服务器硬盘整体ghost,GHOST备份