maven学习笔记

一、由来:

不使用maven,项目往往会存在如下几个问题

现在项目中存在一个问题

1.以前划分模块:以package来划分,最好每一个模块对应一个工程,借助于maven可以将项目拆分成多个工程。

2.项目中需要的jar包必须手动“复制”、粘贴到WEB-INF/lib目录下,不同项目中的jar包会重复出现,maven可以放放仓库中,需要使用时,引用即可(可联想到运行时环境。。。。运行时环境也是引用了jar包)

3.jar包需要到官网下,使用maven可以以一种规范的方式下载jar包。所有知名框架或者第三方工具的jar包都已经按照统一规范🏡maven的中央仓库中。

tips:“统一的规范”非常重要

4.一个jar包依赖其他jar需要手动加入到项目中,依赖易冲突

maven 的作用

  1.解决 以上所有问题;若项目大了,每个模块可以独立为一个工程;jar包可以通过pom.xml来进行管理,不用手动去下载jar包并且加入项目中,直接去中央仓库获取依赖信息即可;

  2.maven是一款服务于Java平台的自动化构建平台;构建工具发展过程:Mark-->Ant-->maven-->gradle;现在的项目使用maven 居多;

maven 安装(要有java环境 即 安装了jdk)

  1. 下载maven;解压maven压缩包,非中文无空格的目录下;
  2. 配置maven的环境:

    ①、右键---计算机属性----高级系统设置---高级---环境变量---系统变量----新建;如图1; 

      变量名:MAVEN_HOME

      变量值:这个值是 maven 压缩包解压的位置

   ②、将 MAVEN_HOME 添加到 path 目录下

    选择 path---编辑---新建---将 %MAVEN_HOME%\bin  添加进去,然后点击确定就可以了

    ③运行mvn -v:出现版本号表明安装成功

                   

构建:

  以“Java源文件”,“框架配置文件”,“jsp”,“图片”等资源为原材料,去生产一个可以运行的项目的过程;

构建过程中的各个环节:

    清理:删除旧的class文件

    编译:把Java源程序编译成class字节码

    测试:自动测试,自动调用Junit

    报告:测试程序执行结果

    打包:动态web工程打的是war,Java工程打jar包

    安装:将打包得到的文件复制到仓库中的指定位置;

    部署:将war包复制到servlet容器的指定目录下。

 

maven核心概念:

1.约定的目录结构

遵守约定的目录结构的目的:maven 要负责项目的自动化构建,以编译为例,maven要想自动进行编译,那么他必须要知道java源文件在南里。

如果我们自己自定义的东西想要让框架或工具知道,有两种方式

1.以配置的方式明确告诉 框架;

2.遵守框架内部已经存在的约定;

Hello

|----src

|----|----main

|----|----|---java

|----|----|---resource

|----|----test

|----|----|---java

|----|----|---resource

|----pom.xml 

  • 根目录:项目名称
  • src:源码
  • pom.xml
  • main:存放主程序
  • test:测试程序
  • Java:Java源文件
  • resources:配置文件/其他工具的配置文件。。。。。

2.pom:

  • 含义:project object model 项目对象模型

      dom document object model 文档对象模型

  • pom.xml是maven工程的核心配置文件,与构建过程相关的一起设置都在这个文件中配置

      重要程度相对于web.xml

3.坐标:

  groupId:公司/组织 域名倒叙+项目名称; 例如:org.apache.commons;一般分为多个段,第一段为域(org、com、cn...),第二段为公司名,最后是项目名称;

  artifactId:模块名称;例如:commons-lang3  ;实际项目中的一个Maven项目或者是子模块名称 ;

  version:当前版本 例如:3.12.0

  packaging:打包方式,最为常见的jar和war两种

4.依赖:

  说明:依赖是pom.xml中的一个标签:

View Code
  • 依赖的范围:

依赖范围scope用来控制依赖和编译,测试,运行的classpath的关系. 主要的是三种依赖关系如下:

    ①compile 默认编译依赖范围。对于编译,测试,运行三种classpath都有效 

    ②test:测试依赖范围。只对于测试classpath有效

    ③provided:已提供依赖范围。对于编译,测试的classpath都有效,但对于运行无效。因为由容器已经提供,例如servlet-api

    ④runtime:运行时提供。例如:jdbc驱动

  • 依赖的传递性:

   MakeFriends.jar直接依赖于HelloFriends.jar,而HelloFriends.jar又直接依赖于Hello.jar,那么MakeFriends.jar也依赖于Hello.jar,这就是传递性依赖,只不过这种依赖是间接依赖,

  • 对于我们自己创建的maven 工程,使用maven install命令就可以进入maven仓库;
  • 依赖排除:
1 <executions>  
2     <execution>  
3         <id>cargo-run</id>  
4         <phase>install</phase>  
5         <goals>  
6             <goal>run</goal>  
7         </goals>  
8     </execution>  
9 </executions>
  •  依赖原则:路径最短者优先、路径相同时先声明者优先;

  Hello<--HelloFriend<--MakeFriends

[1]在Hello中依赖log4j-1.2.17
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

[2]在HelloFriend中依赖log4j-1.2.14
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
[3]查看MakeFriends中自动引入的log4j是哪个版本?  2.14

MakeFriends<--OurFriends
[1]创建OurFriends工程,依赖log4j-1.2.17
[2]让MakeFriends依赖OurFriends
[3]测试MakeFriends中,HelloFriend和OurFriends依赖的先后顺序和引入的log4j版本之间的  

  •  依赖版本的统一管理:
    <properties>
            <org.muses.spring.versin>5.3.0</org.muses.spring.versin>
        </properties>
    1 <dependency>
    2             <groupId>org.springframework</groupId>
    3             <artifactId>spring-orm</artifactId>
    4             <version>${org.muses.spring.versin}</version>
    5         </dependency>

    properties下的标签,可以设置自定义标签;在对应的地方引用即可;pom.xml完整文件:

     1 <project xmlns="http://maven.apache.org/POM/4.0.0"
     2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
     4     <modelVersion>4.0.0</modelVersion>
     5     <groupId>org.muses.maven</groupId>
     6     <artifactId>webproject-simple</artifactId>
     7     <version>0.0.1-SNAPSHOT</version>
     8     <packaging>war</packaging>
     9     <properties>
    10         <org.muses.spring.versin>5.3.0</org.muses.spring.versin>
    11     </properties>
    12 
    13     <dependencies>
    14         <dependency>
    15             <groupId>javax.servlet</groupId>
    16             <artifactId>servlet-api</artifactId>
    17             <version>2.5</version>
    18             <scope>provided</scope>
    19         </dependency>
    20         <dependency>
    21             <groupId>javax.servlet.jsp</groupId>
    22             <artifactId>jsp-api</artifactId>
    23             <version>2.1.3-b06</version>
    24             <scope>provided</scope>
    25         </dependency>
    26         <dependency>
    27             <groupId>org.springframework</groupId>
    28             <artifactId>spring-orm</artifactId>
    29             <version>${org.muses.spring.versin}</version>
    30         </dependency>
    31     </dependencies>
    32 </project>
    View Code

     

5.仓库:

分为本地仓库和远程仓库;

本地仓库默认是:默认是在~/.m2/repository/,~代表的是用户目录;

远程仓库 分为中央仓库和私服。默认是maven的中央仓库:https://mvnrepository.com/

 仓库配置:https://www.cnblogs.com/lixiuming521125/p/15854378.html 

6.生命周期/插件/目标:

maven 有三个独立的生命周期,clean、default、site。每个生命周期包含一些生命周期阶段,这些阶段是有顺序的,后面的阶段依赖于前面的阶段。

clean生命周期包含的阶段:pre-clean、clean、post-clean 

default生命周期包含的阶段:
1 process-sources、2 compile、3 process-test-sources、4 test-compile、5 test、6 package、 verify、8 install、9 deploy
1 处理主资源文件、2 编译主代码、3 处理测试资源文件、4 编译测试代码、5 运行测试、6 将编译好的代码打包、---- 、8 将包安装到本地仓库、9 将包安装到远程仓库

site生命周期包含的阶段:
pre-site、site(生成项目站点文档)、post-site、site-deploy(把生成的项目站点发布到服务器上)

7.继承 

现在:各个工程依赖的Junit版本不同,hello 依赖Junit:4.0;hellofriend依赖Junit:4.0;makefriend依赖的Junit:4.9

需求:统一管理各个模块工程中对Junit依赖的版本

test范围的依赖,因为不能传递,所以会分散。

  解决思路:将Junit依赖版本统一提取到父工程中,在子工程中声明依赖时不指定版本,以父工程中设定为准,便于修改,

        1.创建一个maven工程作为父工程,注意,打包方式为pom

        2.子工程中声明对父工程的引用,在子工程中声明父工程

          <parent>

            <groupId>com.atguigu.maven</groupId>

            <artifactId>Parent</artifactId>

            <version>0.0.1-SNAPSHOT</version>

            <!-- 以当前工程的pom.xml文件为基准的父工程POM.XML文件的相对路径 -->

            <relativePath>../Panrent/pom.xml</relativePath>

           </parent>

       参考子类工程的pom.xml 

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <name>lean-mgt.mock</name>
  <artifactId>lean-mgt.mock</artifactId>
  <packaging>war</packaging>
  
  <parent>
    <groupId>org.frends.learn</groupId>
    <artifactId>learn-mgt</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>lean-mgt.mock</finalName>
  </build>
</project>
View Code

      3.将子工程的坐标与父工程坐标中重复的内容删除,会有提示,不删也可以

      4.在父工程中统一声明Junit依赖

        <!-- 配置依赖的管理 -->

         <dependencyManagement>

            <dependencies>

            <dependency>

             <groupId>junit</groupId>

               <artifactId>junit</artifactId>

               <version>4.9</version>

             </dependency>

           </dependencies>

         </dependencyManagement>

     5.在子工程中,删除Junit的依赖的版本号,若不删除,则以子类的Junit版本号为准

      注意:配置继承后,若要安装,则要先安装父工程,否则会报错:找不到父工程

补充:

Maven中的dependencyManagement元素提供了一种管理依赖版本号的方式。在dependencyManagement元素中声明所依赖的jar包的版本号等信息,那么所有子项目再次引入此依赖jar包时则无需显式的列出版本号。Maven会沿着父子层级向上寻找拥有dependencyManagement 元素的项目,然后使用它指定的版本号

8.聚合

  • 作用:一键安装各个模块工程
  • 配置方式:在一个“总的聚合工程”

        <!-- 配置聚合 -->

        <modules>

          <!-- 指定子工程的相对路径 -->

          <module>../Hello</module>

        </modules>

  • 使用方式:在父工程的pom.xml--》右键run as--》maven install

参考 聚会的pom.xml

<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.frends.learn</groupId>
  <artifactId>learn-mgt</artifactId>
  <packaging>pom</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>learn-mgt</name>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>learn-mgt</finalName>
  </build>
  <modules>
      <module>lean-mgt.mock</module>
  </modules>
</project>
View Code

关于联网的问题

maven 核心程序仅定义了生命周期,具体的工作还是需要特定的插件来完成,而插件本身并不包含在maven的核心程序中1当执行的maven的命令,需要用到的插件时,先到本地仓库查看,默认本地仓库为当前家目录;当maven核心程序如果在本地仓库中找不到需要的插件,那么他自动连接到外网,到中央仓库下载,如果连不到外网,则构建失败;;

本地仓库的默认位置:系统中当前用户的家目录\.m2\repository;eg. c:\Users\当前系统的用户名\.m2\repository;

修改本地仓库的位置,可以让maven核心程序到我们事先准备好的目录下查找插件;

  1. 找到maven解压目录\config\settings.xml
  2. 在settings.xml中找到localRepository标签
  3. 将<localRepository>/path/to/local/repo</localRepository>从注释中取出,
  4. 将标签体内容修改为已经准备好的maven仓库目录;
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 
  3 <!--
  4 Licensed to the Apache Software Foundation (ASF) under one
  5 or more contributor license agreements.  See the NOTICE file
  6 distributed with this work for additional information
  7 regarding copyright ownership.  The ASF licenses this file
  8 to you under the Apache License, Version 2.0 (the
  9 "License"); you may not use this file except in compliance
 10 with the License.  You may obtain a copy of the License at
 11 
 12     http://www.apache.org/licenses/LICENSE-2.0
 13 
 14 Unless required by applicable law or agreed to in writing,
 15 software distributed under the License is distributed on an
 16 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 17 KIND, either express or implied.  See the License for the
 18 specific language governing permissions and limitations
 19 under the License.
 20 -->
 21 
 22 <!--
 23  | This is the configuration file for Maven. It can be specified at two levels:
 24  |
 25  |  1. User Level. This settings.xml file provides configuration for a single user,
 26  |                 and is normally provided in ${user.home}/.m2/settings.xml.
 27  |
 28  |                 NOTE: This location can be overridden with the CLI option:
 29  |
 30  |                 -s /path/to/user/settings.xml
 31  |
 32  |  2. Global Level. This settings.xml file provides configuration for all Maven
 33  |                 users on a machine (assuming they're all using the same Maven
 34  |                 installation). It's normally provided in
 35  |                 ${maven.conf}/settings.xml.
 36  |
 37  |                 NOTE: This location can be overridden with the CLI option:
 38  |
 39  |                 -gs /path/to/global/settings.xml
 40  |
 41  | The sections in this sample file are intended to give you a running start at
 42  | getting the most out of your Maven installation. Where appropriate, the default
 43  | values (values used when the setting is not specified) are provided.
 44  |
 45  |-->
 46 <settings xmlns="http://maven.apache.org/SETTINGS/1.2.0"
 47           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 48           xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 https://maven.apache.org/xsd/settings-1.2.0.xsd">
 49   <!-- localRepository
 50    | The path to the local repository maven will use to store artifacts.
 51    |
 52    | Default: ${user.home}/.m2/repository
 53   <localRepository>/path/to/local/repo</localRepository>
 54   -->
 55 <localRepository>/Users/lixiuming/.m2/repository</localRepository>
 56   <!-- interactiveMode
 57    | This will determine whether maven prompts you when it needs input. If set to false,
 58    | maven will use a sensible default value, perhaps based on some other setting, for
 59    | the parameter in question.
 60    |
 61    | Default: true
 62   <interactiveMode>true</interactiveMode>
 63   -->
 64 
 65   <!-- offline
 66    | Determines whether maven should attempt to connect to the network when executing a build.
 67    | This will have an effect on artifact downloads, artifact deployment, and others.
 68    |
 69    | Default: false
 70   <offline>false</offline>
 71   -->
 72 
 73   <!-- pluginGroups
 74    | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
 75    | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
 76    | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
 77    |-->
 78   <pluginGroups>
 79     <!-- pluginGroup
 80      | Specifies a further group identifier to use for plugin lookup.
 81     <pluginGroup>com.your.plugins</pluginGroup>
 82     -->
 83   </pluginGroups>
 84 
 85   <!-- proxies
 86    | This is a list of proxies which can be used on this machine to connect to the network.
 87    | Unless otherwise specified (by system property or command-line switch), the first proxy
 88    | specification in this list marked as active will be used.
 89    |-->
 90   <proxies>
 91     <!-- proxy
 92      | Specification for one proxy, to be used in connecting to the network.
 93      |
 94     <proxy>
 95       <id>optional</id>
 96       <active>true</active>
 97       <protocol>http</protocol>
 98       <username>proxyuser</username>
 99       <password>proxypass</password>
100       <host>proxy.host.net</host>
101       <port>80</port>
102       <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
103     </proxy>
104     -->
105   </proxies>
106 
107   <!-- servers
108    | This is a list of authentication profiles, keyed by the server-id used within the system.
109    | Authentication profiles can be used whenever maven must make a connection to a remote server.
110    |-->
111   <servers>
112     <!-- server
113      | Specifies the authentication information to use when connecting to a particular server, identified by
114      | a unique name within the system (referred to by the 'id' attribute below).
115      |
116      | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
117      |       used together.
118      |
119     <server>
120       <id>deploymentRepo</id>
121       <username>repouser</username>
122       <password>repopwd</password>
123     </server>
124     -->
125 
126     <!-- Another sample, using keys to authenticate.
127     <server>
128       <id>siteServer</id>
129       <privateKey>/path/to/private/key</privateKey>
130       <passphrase>optional; leave empty if not used.</passphrase>
131     </server>
132     -->
133   </servers>
134 
135   <!-- mirrors
136    | This is a list of mirrors to be used in downloading artifacts from remote repositories.
137    |
138    | It works like this: a POM may declare a repository to use in resolving certain artifacts.
139    | However, this repository may have problems with heavy traffic at times, so people have mirrored
140    | it to several places.
141    |
142    | That repository definition will have a unique id, so we can create a mirror reference for that
143    | repository, to be used as an alternate download site. The mirror site will be the preferred
144    | server for that repository.
145    |-->
146   <mirrors>
147     <!-- mirror
148      | Specifies a repository mirror site to use instead of a given repository. The repository that
149      | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
150      | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
151      |
152     <mirror>
153       <id>mirrorId</id>
154       <mirrorOf>repositoryId</mirrorOf>
155       <name>Human Readable Name for this Mirror.</name>
156       <url>http://my.repository.com/repo/path</url>
157     </mirror>
158      -->
159     <mirror>
160       <id>maven-default-http-blocker</id>
161       <mirrorOf>external:http:*</mirrorOf>
162       <name>Pseudo repository to mirror external repositories initially using HTTP.</name>
163       <url>http://0.0.0.0/</url>
164       <blocked>true</blocked>
165     </mirror>
166   </mirrors>
167 
168   <!-- profiles
169    | This is a list of profiles which can be activated in a variety of ways, and which can modify
170    | the build process. Profiles provided in the settings.xml are intended to provide local machine-
171    | specific paths and repository locations which allow the build to work in the local environment.
172    |
173    | For example, if you have an integration testing plugin - like cactus - that needs to know where
174    | your Tomcat instance is installed, you can provide a variable here such that the variable is
175    | dereferenced during the build process to configure the cactus plugin.
176    |
177    | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
178    | section of this document (settings.xml) - will be discussed later. Another way essentially
179    | relies on the detection of a system property, either matching a particular value for the property,
180    | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
181    | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
182    | Finally, the list of active profiles can be specified directly from the command line.
183    |
184    | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
185    |       repositories, plugin repositories, and free-form properties to be used as configuration
186    |       variables for plugins in the POM.
187    |
188    |-->
189   <profiles>
190     <!-- profile
191      | Specifies a set of introductions to the build process, to be activated using one or more of the
192      | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
193      | or the command line, profiles have to have an ID that is unique.
194      |
195      | An encouraged best practice for profile identification is to use a consistent naming convention
196      | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
197      | This will make it more intuitive to understand what the set of introduced profiles is attempting
198      | to accomplish, particularly when you only have a list of profile id's for debug.
199      |
200      | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
201     <profile>
202       <id>jdk-1.4</id>
203 
204       <activation>
205         <jdk>1.4</jdk>
206       </activation>
207 
208       <repositories>
209         <repository>
210           <id>jdk14</id>
211           <name>Repository for JDK 1.4 builds</name>
212           <url>http://www.myhost.com/maven/jdk14</url>
213           <layout>default</layout>
214           <snapshotPolicy>always</snapshotPolicy>
215         </repository>
216       </repositories>
217     </profile>
218     -->
219 
220     <!--
221      | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
222      | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
223      | might hypothetically look like:
224      |
225      | ...
226      | <plugin>
227      |   <groupId>org.myco.myplugins</groupId>
228      |   <artifactId>myplugin</artifactId>
229      |
230      |   <configuration>
231      |     <tomcatLocation>${tomcatPath}</tomcatLocation>
232      |   </configuration>
233      | </plugin>
234      | ...
235      |
236      | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
237      |       anything, you could just leave off the <value/> inside the activation-property.
238      |
239     <profile>
240       <id>env-dev</id>
241 
242       <activation>
243         <property>
244           <name>target-env</name>
245           <value>dev</value>
246         </property>
247       </activation>
248 
249       <properties>
250         <tomcatPath>/path/to/tomcat/instance</tomcatPath>
251       </properties>
252     </profile>
253     -->
254   </profiles>
255 
256   <!-- activeProfiles
257    | List of profiles that are active for all builds.
258    |
259   <activeProfiles>
260     <activeProfile>alwaysActiveProfile</activeProfile>
261     <activeProfile>anotherAlwaysActiveProfile</activeProfile>
262   </activeProfiles>
263   -->
264 </settings>
View Code 

常用命令:

    执行与构建过程相关的命令:必须进入pom.xml目录

    mvn clean:清楚

    mvn compile:编译,还可能会自动下载东西

    mvn test-compile:测试编译

    mvn test:测试

    mvn package:打包

官方文档地址:

https://maven.apache.org/guides/getting-started/index.html

posted @ 2018-01-05 15:12  啄木鸟伍迪  阅读(292)  评论(0编辑  收藏  举报
//火箭 GenerateContentList();