Maven日常 —— 你应该知道的一二三
1 什么是Maven?
如果沒有Maven,你可能不得不經歷下面的過程:
1 如果使用了spring,去spring的官網下載jar包;如果使用hibernate,去hibernate的官網下載Jar包;如果使用Log4j,去log4j的官網下載jar包.....
2 當某些jar包有依賴的時候,還要去下載對應的依賴jar包
3 當jar包依賴有沖突時,不得不一個一個的排查
4 執行構建時,需要使用ant寫出很多重復的任務代碼
5 當新人加入開發時,需要拷貝大量的jar包,然后重復進行構建
6 當進行測試時,需要一個一個的運行....檢查
有了Maven,它提供了三種功能:
1 依賴的管理:僅僅通過jar包的幾個屬性,就能確定唯一的jar包,在指定的文件pom.xml中,只要寫入這些依賴屬性,就會自動下載并管理jar包。
2 項目的構建:內置很多的插件與生命周期,支持多種任務,比如校驗、編譯、測試、打包、部署、發布...
3 項目的知識管理:管理項目相關的其他內容,比如開發者信息,版本等等
2 Maven如何管理jar包
關于jar包的坐標,有過使用經驗的都應該有所了解,maven是通過groupId,artifactId,以及version確定一個唯一的jar包。
這部分的內容可以參考前一篇:構建過程
例如,最常使用的Junit的聲明就是如下:
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope> 這是聲明的范圍,不同的生命周期所要求的范圍是不一樣的,詳情參考《Maven實戰》 </dependency>首先先來說說Maven下載jar包的過程:
在Maven中會涉及到幾種倉庫:
1 工作空間,即我們的項目工程,這里面可能會放著pom.xml文件,這個pom.xml就是maven的配置文件
2 本地倉庫,本地倉庫用于存放jar包,其實Jar包并不是直接放入工作空間的,它是存放在本地倉庫,然后在執行發布打包的時候,添加依賴路徑
3 私庫:私庫是使用者自己搭建的maven倉庫,用于緩解頻繁從外網下載jar包資源的壓力。而且使用私庫作為緩存層,也相對安全一些。
4 共享倉庫:書中所說的中央倉庫或者一些常用的鏡像網站都屬于這種,國內比較著名的oschina以及163都是不錯的maven倉庫。
當我們在pom中聲明了依賴關系后,參考上面的圖:
1 Maven在執行相關的任務時,會先去本地倉庫查看是否有該資源,如果有的話,判斷版本是否正確,如果一切都沒問題則直接使用;否則,執行下一步
2 Maven會去配置的共享倉庫中查找,如果找到就拷貝到本地倉庫中;找不到則會給出相關的提示
3?Maven在本地如果搭建了私庫,則會去私庫中查找,找到就拷貝到本地倉庫;找不到就會去共享倉庫中查找,然后放入私庫和本地庫。有了私庫,局域網內的開發者可以共享依賴,就不用每個人都去外網下載jar包,浪費帶寬了。
關于本地倉庫和共享倉庫的配置都在settings.xml中,這個文件位于conf中,如果沒有則拷貝一份即可。
<?xml version="1.0" encoding="UTF-8"?><!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --><!--| This is the configuration file for Maven. It can be specified at two levels:|| 1. User Level. This settings.xml file provides configuration for a single user,| and is normally provided in ${user.home}/.m2/settings.xml.|| NOTE: This location can be overridden with the CLI option:|| -s /path/to/user/settings.xml|| 2. Global Level. This settings.xml file provides configuration for all Maven| users on a machine (assuming they're all using the same Maven| installation). It's normally provided in| ${maven.home}/conf/settings.xml.|| NOTE: This location can be overridden with the CLI option:|| -gs /path/to/global/settings.xml|| The sections in this sample file are intended to give you a running start at| getting the most out of your Maven installation. Where appropriate, the default| values (values used when the setting is not specified) are provided.||--> <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"><!-- localRepository| The path to the local repository maven will use to store artifacts.|| Default: ${user.home}/.m2/repository<localRepository>/path/to/local/repo</localRepository>--><!-- interactiveMode| This will determine whether maven prompts you when it needs input. If set to false,| maven will use a sensible default value, perhaps based on some other setting, for| the parameter in question.|| Default: true<interactiveMode>true</interactiveMode>--><!-- offline| Determines whether maven should attempt to connect to the network when executing a build.| This will have an effect on artifact downloads, artifact deployment, and others.|| Default: false<offline>false</offline>--><!-- pluginGroups| This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.| when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers| "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.|--><pluginGroups><!-- pluginGroup| Specifies a further group identifier to use for plugin lookup.<pluginGroup>com.your.plugins</pluginGroup>--></pluginGroups><!-- proxies| This is a list of proxies which can be used on this machine to connect to the network.| Unless otherwise specified (by system property or command-line switch), the first proxy| specification in this list marked as active will be used.|--><proxies><!-- proxy| Specification for one proxy, to be used in connecting to the network.|<proxy><id>optional</id><active>true</active><protocol>http</protocol><username>proxyuser</username><password>proxypass</password><host>proxy.host.net</host><port>80</port><nonProxyHosts>local.net|some.host.com</nonProxyHosts></proxy>--></proxies><!-- servers| This is a list of authentication profiles, keyed by the server-id used within the system.| Authentication profiles can be used whenever maven must make a connection to a remote server.|--><servers><!-- server| Specifies the authentication information to use when connecting to a particular server, identified by| a unique name within the system (referred to by the 'id' attribute below).|| NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are| used together.|<server><id>deploymentRepo</id><username>repouser</username><password>repopwd</password></server>--><!-- Another sample, using keys to authenticate.<server><id>siteServer</id><privateKey>/path/to/private/key</privateKey><passphrase>optional; leave empty if not used.</passphrase></server>--></servers><!-- mirrors| This is a list of mirrors to be used in downloading artifacts from remote repositories.|| It works like this: a POM may declare a repository to use in resolving certain artifacts.| However, this repository may have problems with heavy traffic at times, so people have mirrored| it to several places.|| That repository definition will have a unique id, so we can create a mirror reference for that| repository, to be used as an alternate download site. The mirror site will be the preferred| server for that repository.|--><mirrors><!-- mirror| Specifies a repository mirror site to use instead of a given repository. The repository that| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.|<mirror><id>mirrorId</id><mirrorOf>repositoryId</mirrorOf><name>Human Readable Name for this Mirror.</name><url>http://my.repository.com/repo/path</url></mirror>--></mirrors><!-- profiles| This is a list of profiles which can be activated in a variety of ways, and which can modify| the build process. Profiles provided in the settings.xml are intended to provide local machine-| specific paths and repository locations which allow the build to work in the local environment.|| For example, if you have an integration testing plugin - like cactus - that needs to know where| your Tomcat instance is installed, you can provide a variable here such that the variable is| dereferenced during the build process to configure the cactus plugin.|| As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles| section of this document (settings.xml) - will be discussed later. Another way essentially| relies on the detection of a system property, either matching a particular value for the property,| or merely testing its existence. Profiles can also be activated by JDK version prefix, where a| value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.| Finally, the list of active profiles can be specified directly from the command line.|| NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact| repositories, plugin repositories, and free-form properties to be used as configuration| variables for plugins in the POM.||--><profiles><!-- profile| Specifies a set of introductions to the build process, to be activated using one or more of the| mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>| or the command line, profiles have to have an ID that is unique.|| An encouraged best practice for profile identification is to use a consistent naming convention| for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.| This will make it more intuitive to understand what the set of introduced profiles is attempting| to accomplish, particularly when you only have a list of profile id's for debug.|| This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.<profile><id>jdk-1.4</id><activation><jdk>1.4</jdk></activation><repositories><repository><id>jdk14</id><name>Repository for JDK 1.4 builds</name><url>http://www.myhost.com/maven/jdk14</url><layout>default</layout><snapshotPolicy>always</snapshotPolicy></repository></repositories></profile>--><!--| Here is another profile, activated by the system property 'target-env' with a value of 'dev',| which provides a specific path to the Tomcat instance. To use this, your plugin configuration| might hypothetically look like:|| ...| <plugin>| <groupId>org.myco.myplugins</groupId>| <artifactId>myplugin</artifactId>|| <configuration>| <tomcatLocation>${tomcatPath}</tomcatLocation>| </configuration>| </plugin>| ...|| NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to| anything, you could just leave off the <value/> inside the activation-property.|<profile><id>env-dev</id><activation><property><name>target-env</name><value>dev</value></property></activation><properties><tomcatPath>/path/to/tomcat/instance</tomcatPath></properties></profile>--></profiles><!-- activeProfiles| List of profiles that are active for all builds.|<activeProfiles><activeProfile>alwaysActiveProfile</activeProfile><activeProfile>anotherAlwaysActiveProfile</activeProfile></activeProfiles>--> </settings>其中本地倉庫的配置為:
<localRepository>F:\apache-maven-3.3.9\repo</localRepository>默認是在?用戶的本地目錄/.m2/repository中。
共享倉庫的地址配置為:
<mirrors><mirror><id>CN</id><name>OSChina Central</name> <url>http://maven.oschina.net/content/groups/public/</url><mirrorOf>central</mirrorOf></mirror></mirrors>3 Maven的生命周期與階段
Maven中有三大生命周期,他們相互獨立,分別是:
1 clean 清理
2 default 構建
3 site 建站
一般來說,clean和default比較常用。
每個生命周期又有不同的階段,階段按順序執行,并且可以指定執行結束的階段。構建的時候,會依次從最上面的階段執行到指定的那個階段。
比如,clean有3個階段:
1 pre-clean 執行清理前要完成的工作 2 clean 清理上一次構建生成的文件 3 post-clean 執行清理后需要完成的工作當我們輸入mvn clean的時候,執行的是pre-clean和clean兩個階段。
default的階段比較多:
1 validate 2 initialize 3 generate-sources 4 process-sources 5 generate-resources 6 process-resources 7 compile 8 process-classes 9 generate-test-sources 10 process-test-sources 11 generate-test-resources 12 process-test-resources 13 test-compile 14 process-test-classes 15 tet 16 prepare-package 17 package 18 pre-integration-test 19 integration-test 20 post-integration-test 21 verify 22 install 23 deploy看名字大概就能理解,當執行mvn install的時候,實際會執行validate-->initialize-->...-->verify-->install等二十幾個階段。
為了操作方便,不同的聲明周期可以在一起執行,比如mvn clean install,會先執行clean的階段,在執行install的階段。
在IDE開發環境中,當我們Run as的時候,就可以執行maven clean進行清理,或者執行maven install進行構建,也可以執行maven build同時執行clean和install兩個任務。
基本上了解上面兩個知識點,就足夠日常工作使用了。當然Maven可不止這么一點點的東西,比如它還涉及到自定義構建任務、間接依賴的管理、插件的使用、私庫的搭建等等,如果需要的話,讀者可以參考《Maven實戰》,這本書講述的很全面了。
總結
以上是生活随笔為你收集整理的Maven日常 —— 你应该知道的一二三的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么查询自己股票账户什么时候开户的
- 下一篇: 一万元怎么理财收益大 可以选择这些理财