maven是一種很是流行的項目管理工具,它將項目依賴的jar包都變成了配置文件---pom.xml。java
maven經過pom文件讀取須要哪些依賴包,而後到網上mavenRepository下載依賴包到本地。用到的依賴包以及相關文件都會下載到指定本地目錄中,造成本地庫。在編譯項目時,再引入你的項目中。linux
結構以下圖:git
maven源網址在國外,下載依賴包很是的緩慢甚至失敗,因此想要順暢得使用maven,還須要配置國內鏡像。具體操做見下文github
它的優點在於maven結構的項目源碼很是小,將動輒幾MB,幾十MB的依賴jar包,變成了幾十個字節的配置文件。將項目源碼從幾百MB縮減到不到1MB,利於下載與上傳。在github開源社區上使用很是普遍。web
幾乎全部發布的jar包都已經支持maven,在各自的pom文件中,標註依賴了哪些jar包以及版本號。這樣,maven就能夠將多級依賴包都一併下載。大大簡化依賴包下載工做。spring
發生依賴衝突時,找到引入依賴包的配置並去除(exclusion)依賴便可。經過使用界面化工具能夠更方便得完成去除依賴操做。具體操做見下文apache
這裏都使用eclipse來作說明,eclipse自帶maven插件。windows
菜單欄 File --> new --> project ,搜索maven,選擇maven projectapp
勾選 create a simple project (skip archetype selection),創建簡單的項目,不使用模板。eclipse
建立完成後 結構以下
經常使用路徑說明:
其餘:
建議使用maven默認的目錄結構,閱讀他人,或者他人在閱讀你的代碼將變得更容易。使用非默認結構也能夠在pom文件中進行配置。
項目名右鍵 --> configure --> convert to maven project 便可
因爲普通java項目與maven項目結構不一樣,須要移動原有文件到默認maven結構目錄下,或者在pom文件中進行目錄配置。
maven結構的項目,其項目配置都寫在pom文件中,項目刷新須要使用 ALT+F5, 或者 項目名右鍵 --> maven --> update project。
pom裏面除了配置依賴包,還有jdk版本、打包的配置(web包、可執行jar)等等。
pom文件中的配置項很是豐富,這裏只作一些簡單介紹。
mavenRepository網站上搜索選擇你想要的依賴包名稱,如spring-core
選擇一箇中意的版本
複製配置到pom文件中dependencies標籤下便可。
maven根目錄在C:\Users\{用戶名}\.m2\
修改maven根目錄下的conf文件夾中的setting.xml文件,內容以下:
<mirrors> <mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> </mirrors>
以後就能享受如飛的maven下載速度。
例如去除 common-logging 依賴
eclipse中打開pom文件切換到Dependency Hierarchy頁面
選中commons-logging,右鍵 exclude maven artifact... 保存
依賴中commons-logging就消失了。
pom文件中表現爲 增長了exclusion 去除了commons-logging
在Maven2中有了明確的生命週期概念,並且都提供與之對應的命令,使得項目構建更加清晰明瞭。主要的生命週期階段:
若是要執行項目編譯,那麼直接輸入:mvn compile便可,對於其餘的階段能夠類推。階段之間是存在依賴關係(dependency)的,如test依賴test-compile。在執行mvn test時,會先運行mvn test-compile,而後纔是mvn test。
這些命令在eclipse中 項目名右鍵 run as --> maven build --> goals 輸入框中使用
pom文件中增長配置
<build> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6.0</version> </plugin> </plugins> </build>
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>***</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build>
***填寫mainClass
<build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> </plugins> </build>
而後執行 maven package
生成打包文件在項目路徑 target目錄下 .jar/.war文件
maven除告終合eclipse使用 ,也是能夠在windows linux下單獨使用的。