Bootstrap

一文带你快速上手项目开发神器Maven

Maven初步学习

前言

你还在网上苦苦找寻项目所依赖的jar包?你还在繁琐地进行手动导入jar包?你是不是很烦这些重复无意义的操作?那么就跟着博主一起来学习Maven吧!Hi~ o( ̄▽ ̄)ブ,本文带你快速拿捏Maven,从此告别去网上搜索下载jar包、手动导jar包的时代^_^

7

1、Maven概述

  • Maven是什么

    Maven是专门用于管理和构建Java项目的工具

    Maven全称Apache Maven,是一个(特别是Java编程)项目管理及自动构建工具,由Apache软件基金会所提供。基于项目对象模型(缩写:POM)概念,Maven利用一个中央信息片断能管理一个项目的构建、报告和文档等步骤,Maven能够很方便的帮你管理项目报告,生成站点,管理JAR文件。

    官网:Maven – 欢迎来到 Apache Maven

    教程:Maven 仓库 | 菜鸟教程

  • Maven的功能

    1)提供一套标准化的项目结构。让所有的IDE1使用Maven构建的项目结构完全一样,从而让Maven构建的项目有更高的移植性

    2)提供一套标准化的项目构建流程( 编译 → 测试 → 打包 → 发布 编译\rightarrow{测试}\rightarrow{打包}\rightarrow{发布} 编译测试打包发布)。只需要敲一些简单的命令就能很快完成项目的创建,从而提高创建项目的效率

    3)提供一套依赖管理2机制。只需要一个简单的配置就可以告别手动导入jar包了

  • Maven模型图

image-20220723223231601

备注

  1. 仓库可分为:本地仓库3、远程仓库4、中央仓库5✈️传送门

  • Maven仓库访问流程

    1)访问中央仓库:

    image-20220724134517872

    访问的具体过程:Java项目先到本地仓库中去找项目所需要引用的jar包,如果本地仓库没有该jar包,再去中央仓库中去找,找到就会直接将该jar包下载到本地仓库中,然后项目在进行引用。

    可能你会疑惑如果中央仓库中也没有该jar包怎么办。这个就不太需要担心了,中央仓库是Apache进行维护的,里面包含了几乎项目中所有常用的jar包,如果真的没有,那么你也只能自己去网上找了,然后下载到本地仓库中,但这件事的概率很低。

    2)访问远程仓库:(企业中常用的方式

    image-20220724134621153

    访问的具体过程:Java项目先到本地仓库中去找项目所需要引用的jar包,如果本地仓库没有该jar包,再去远程仓库中找,远程仓库没有再到中央仓库中找,找到以后就将该jar包下载到远程仓库和本地仓库,然后就可以再项目中引用了。

    可能你有这样的疑惑这种方式看上去比比访问中央仓库要麻烦得多,为什么还要企业里面还常用。中央仓库是在国外,我们国内访问会很慢(像访问GitHub一样,我们一般会使用国内的Gitee来代替),同时也存在一定的安全隐患(不能过渡依赖别人),而使用远程仓库就会很快,同时更安全,并且这种方式也不是很麻烦,远程仓库一般都会拷贝中央仓库中的所有jar包,并且还能导入公司自己开发的jar包。

当jar包被本地仓库引用后,以后再进行引用就不需要去下载了

2、Maven安装

安装Maven
配置Maven环境
查询是否配置成功
配置仓库
  • Step1:安装Maven。Maven是一款绿色轻量级软件,直接解压即可使用。下载地址:这里

    Maven安装后:

    image-20220724132545135

  • Step2:配置环境变量。

    右击此电脑 → 高级系统设置 → 环境变量 右击此电脑\rightarrow{高级系统设置}\rightarrow{环境变量} 右击此电脑高级系统设置环境变量

    1)配置系统变量。

    image-20220724132805958

    2)配置Path路径。

    image-20220724132937533

  • Step3:查询是否配置成功。·

    image-20220724134443761

备注:如果配置完环境变量后,显示mvn不是系统命令的,可以尝试一下重启电脑

  • Step4:配置本地仓库。

    进入Maven安装目录,然后进入conf文件夹,在进入settings.xml配置文件(推荐使用Notepad++打开)

    1)配置本地仓库:

    image-20220724160754179

    2)配置案例远程仓库:

    image-20220724160458386

相关配置文件:

<?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 at

    http://www.apache.org/licenses/LICENSE-2.0

Unless 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.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>
  -->
  <!--本地仓库路径-->
  <localRepository>D:\soft\安装包\Maven\apache-maven-3.6.1-bin\apache-maven-3.6.1\mvn_resp</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>
     -->
	 <!--阿里云远程仓库地址-->
	 <mirror> <id>alimaven</id> 
	 <name>aliyun maven</name> 
	 <url>http://maven.aliyun.com/nexus/content/groups/public/</url> 
	 <mirrorOf>central</mirrorOf> 
	 </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>

3、Maven常用命令

mvn compile//编译
  • 从阿里云(远程仓库)下载清理需要的插件jar包

  • 删除项目下的 target 目录

mvn clean//清理
  • 从阿里云(远程仓库)下载清理需要的插件的jar包

  • 在项目下会生成一个 target 目录

mvn test//测试
  • 从阿里云(远程仓库)下载测试需要的插件的jar包
  • 该命令会执行所有的测试代码
mvn package//打包
  • 从阿里云(远程仓库)下载打包需要的插件jar包
  • 在项目的 terget 目录下有一个jar包(将当前项目打成的jar包)
mvn install//安装
  • 从阿里云(远程仓库)下载安装需要的插件的jar包
  • 该命令会将当前项目打成jar包,并安装到本地仓库

拓展阅读:

powershell和cmd区别是什么

4、Maven生命周期

  生命周期(Life Cycle)的概念应用很广泛,特别是在政治、经济、环境、技术、社会等诸多领域经常出现,其基本涵义可以通俗地理解为“从摇篮到坟墓”(Cradle-to-Grave)的整个过程。

  在Maven中,生命周期就是用来描述Maven构建的项目所经历的的过程(就像人的儿童时期……老年时期),明确项目所处的阶段。Maven中常见的生命周期示意图:

image-20220724165600292

阶段处理描述
验证 validate验证项目验证项目是否正确且所有必须信息是可用的
编译 compile执行编译源代码编译在此阶段完成
测试 Test测试使用适当的单元测试框架(例如JUnit)运行测试。
包装 package打包创建JAR/WAR包如在 pom.xml 中定义提及的包
检查 verify检查对集成测试的结果进行检查,以保证质量达标
安装 install安装安装打包的项目到本地仓库,以供其他项目使用
部署 deploy部署拷贝最终的工程包到远程仓库中,以共享给其他开发人员和工程

Maven对项目构建的生命周期划分为3套:

  • clean :清理工作。

    image-20220724171137853

  • default :核心工作,例如编译,测试,打包,安装等。

    image-20220724171147021

  • site : 产生报告,发布站点等。这套声明周期一般不会使用。

    image-20220724171143887

备注:同一套生命周期内,执行后边的命令,前面的所有命令会被自动执行

5、IDEA中Maven的使用

知识点须知Maven中的坐标

Maven中的坐标是资源的唯一标识。使用坐标来定义项目或引入项目中需要的依赖

Maven 坐标主要组成

  • groupId:定义当前Maven项目隶属组织名称(通常是域名反写,例如:com.hhxy)

  • artifactId:定义当前Maven项目名称(通常是模块名称,例如 order-service、goods-service)

  • version:定义当前项目版本号

  • scope:定义jar包的作用范围。常见有编译环境(compile,这是jar包默认的租用范围)、测试环境(test)、运行环境(runtime)……

    依赖范围编译classpath测试classpath运行classpath例子
    compileYYYlogback
    test-Y-Junit
    providedYY-servlet-api
    runtime-YYjdbc驱动
    systemYY-存储在本地的jar包

5.1 Maven项目的创建和导入

1.Maven项目的创建

配置Maven环境
新建Maven项目

悄悄告诉你们,2022版的IDEA自带最新版Maven,这些琐事(Maven安装、Maven配置文件的设置)都帮我们搞好了,IDEA不愧是Java界最牛逼的工具。大家赶快去拥抱IDEA版吧!

  • Step1配置Maven环境 F i l e → S e t t i n g s → M a v e n File\rightarrow{Settings}\rightarrow{Maven} FileSettingsMaven

    1)集成Maven

image-20220724172015450

2)选择Maven的配置文件

image-20220724172401504

选择自定义的配置文件:

image-20220724172202150

相关配置文件见:这里

  • Step2:新建Maven项目( F i l e → N e w → M o d u l e File\rightarrow{New}\rightarrow{Module} FileNewModule

image-20220724175316652

image-20220724181817001

创建成功后的Maven项目结构:

image-20220724182554496

2.Maven项目的导入

  • Step1:选择右侧Maven面板,点击 + 号

    image-20220724192332173

  • Step2:选中对应项目的pom.xml文件,双击即可

    如果没有右侧没有Maven面板,就进行如下操作:

image-20220724191627243

拓展

上面个的Maven控制面板,虽然可以直接进行Maven生命周期命令的执行,但是当项目多起来的时候,需要找到想要使用的项目,而在真实的项目(特别是大项目)的时候,项目都是成百上千的,找起来很不方便,所以Maven的生命周期指令可以使用一个插件MavenHelp来进行,它不仅可以直接在项目中使用Maven指令,还能进行Debug断点调试。

MavenHelp插件的下载:( F i l e → S e t t i n g s → P l u g i n s File\rightarrow{Settings}\rightarrow{Plugins} FileSettingsPlugins

image-20220724193108392

重启IDEA后生效,右击模块后效果如下:

image-20220724193343023

5.2 使用Maven导入jar包

使用Maven是直接通过设置pom.xml配置文件进行jar包导入,而不需要手动去网上搜索jar包然后进行导入,方便、快捷(也可以使用它来导入插件,方法是一样的)

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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!--项目的坐标信息-->
    <groupId>com.hhxy.maven</groupId><!--项目组织名-->
    <artifactId>day2_maven_demo</artifactId><!--项目模块名-->
    <version>1.0-SNAPSHOT</version><!--项目版本号-->

    <!--JDK的版本-->
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <!--使用坐标导入jar包-->
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
    </dependencies>

</project>

备注

  • 导入jar包的语句可以不写,直接去这个网址进行复制:Maven Repository: Search/Browse/Explore

  • 导入jar包的代码写好后要进行刷新操作(或者Ctrl+S也可以)

  • 也可以使用Alt+Insert快捷键,然后按Dependency进行导入(但是只能导入本地仓库中有的)


  1. IDE(Integrated Development Environment )就是集成开发环境,常见的有:Eclipse、IDEA ↩︎

  2. 依赖管理就是管理项目中所依赖的第三方资源,比如jar包、插件…… ↩︎

  3. 本地仓库(Local Repository):自己计算机上的一个文件夹 ↩︎

  4. 远程仓库(Remote Repository):一般由公司团队搭建的私有仓库 ↩︎

  5. 中央仓库(Central Repository):由Maven团队维护的全球唯一的仓库 ↩︎

;