版本依赖管理之 Maven 修炼手册

简介: 本篇是Maven学习手册,通过本篇学习你将学会为什么使用Maven 依赖?使用Maven依赖和以前的直接引入有什么好处? 你也可以学习到Maven的下载安装配置,以及maven 仓库,maven 坐标,maven 依赖传递,maven依赖范围,maven 插件等基础知识,还可以学习到如何在STS中创建并使用maven 插件运行一个web maven项目。

0x01 为什么使用版本依赖工具Maven?

1.1 仓库简介

  • 没有Maven 时,项目用到的.jar 文件通常需要拷贝到lib目录下,项目多了,拷贝的文件副本就多了,占用磁盘空间,且难以管理。
  • Maven使用 一个称之为仓库的目录,根据构件的坐标统一存储这些构件的唯一副本,在项目中通过依赖声明,可以方便的引用构件。

比如javax.servlet-api-4.0.1.jar 实际存储如图所示:

image

对应的Maven配置就是:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

对应的本地Maven仓库地址文件路径就是:

C:\Users\fairy\.m2\repository\javax\servlet\servlet-api\2.4

1.2 Maven仓库分类

image

  • Maven 仓库分为本地仓库和远程仓库寻找构件时,首先从本地仓库找,找不到则到远程仓库找,再找不到就报错。
  • 在远程仓库中找到了,就下载到本地仓库再使用
  • 中央仓库是Maven核心自带的远程仓库

1.2.1 本地仓库

Maven本地默认仓库地址为:

${user.home}.m2/repository

更改本地仓库位置的方法:

1. 全局修改

修改Maven安装目录下的配置文件

%MAVEN_HOME%/conf/settings.xml

配置如下:

 <!-- 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>${user.home}/.m2/repository</localRepository>
  <!-- 指定本地仓库路径 -->
2. 针对当前用户(推荐)

修改用户目录下的配置文件

${user.home}.m2/settings.xml

共享统用settings.xml配置如下:

 <!-- 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>${user.home}/.m2/repository</localRepository>
  <!-- 指定本地仓库路径 -->

1.2.2 中央仓库

安装完Maven,本地仓库几乎是空的,这时候需要从远程仓库下载所需的构件。
Maven 配置了一个默认的远程仓库即中央仓库。
仓库地址:

<mirrors>
    <mirror>
      <id>UK</id>
      <name>UK Central</name>
      <url>http://uk.maven.org/maven2</url>
      <mirrorOf>central</mirrorOf>
    </mirror>
</mirrors>

美国官方中央仓库地址:

http://repo.maven.apache.org/maven2

英国官方中央仓库地址:

http://uk.maven.org/maven2

阿里云中央仓库地址:

<repository>
          <id>alimaven</id>  
          <name>aliyun maven</name>  
          <url>https://maven.aliyun.com/repository/public</url>
           <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
</repository>

1.3 Maven 坐标

Maven的所有构件都是通过坐标进行组织和管理。maven的坐标通过五个元素进行定义,其中groupId,artifactld,version 是必须的,package 是可选的(默认为jar)
classifier 是不能直接定义的。

  • group :定义当前Maven项目所属的实际项目,跟Java包名类似,通常与域名反向一一对应。
  • artifactId,定义当前Maven项目的一个模块,默认情况下,Maven 生成的构件其文件名会以artifactId 开头,如
    javax.servlet-api-4.0.1.jar
  • version: 定义项目版本
  • packaging:定义项目打包方式,如jar,war,zip... 默认为jar
  • scope:依赖范围,取值有compile,test,provided,默认为compile

1.4 Maven 依赖范围

执行不同的Maven命令(mvn package,mvn test,mvn install......),会使用不同的classpath,运行classpath。
scope选项的值,决定了该依赖构件会被引入到哪一个classpath中。

  • compile:编译依赖范围,默认值。此选项对编译、调试、运行的时候都需要该依赖。
  • test:测试依赖范围。只对测试有效,表明只在测试的时候需要,在编译和运行时将无法使用该依赖,如Junit。
  • provided:已提供依赖范围。编译和测试有效,运行无效。如servlet-api,在项目运行时,tomcat等容易已经提供,无须Maven重复引入

1.5 Maven 依赖传递

image

  • 如上图所示,hibernate-core 依赖hibernate-commons-annotations,而hibernate-commons-annotations又依赖slf4j-api,hibernate对slf4j-api的依赖就是传递依赖,我们只需要引入hibernate-core构件的依赖,不用考虑它还有其他的依赖,也不用担心会引入多余或冲突的依赖,maven 会自动为我们引入依赖和传递其依赖。

1.5 使用Maven好处

  • Maven可以对第三方依赖库进行统一的版本管理。
  • 使用maven可以统一项目的目录结构
  • maven 还支持多种插件
  • 使用maven 可以大大降低项目文件的大小。

0x02 Maven的下载安装配置

  1. 官网下载maven
  2. 解压并配置环境变量:
M2_HOME
C:\Apps\maven\apache-maven-3.6.0

如下所示:
image
3.复制安装目录下的settings.xml到用户目录下
安装目录路径如下:

%MAVEN_HOME%/conf/settings.xml

比如我的就是:

C:\Apps\maven\apache-maven-3.6.0\conf\setings.xml

用户目录路径如下:

${user.home}.m2/repository

比如我们的就是:

C:\Users\fairy\.m2\settings.xml
  1. 配置settings.xml
<?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.
-->

<!-- Maven Configuration Guide http://maven.apache.org/settings.html -->
<!--
 | 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>${user.home}/.m2/repository</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>
  -->
   <interactiveMode>true</interactiveMode>
   <!-- 如果认为Maven应该尝试与用户进行交互以进行输入,使用true,否则返回false。 默认为true。-->

  <!-- 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>
   | 是否启用离线模式,默认是false
   | 如果改为true表示启用离线模式,即只加载本地仓库Jar包不支持联网下载
   | 如果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>
    -->
    <!-- 使用下面配置后 org.mortbay.jetty:jetty-maven-plugin:run 可以简写成 mvn jetty:run -->
    <pluginGroup>org.mortbay.jetty</pluginGroup>
    <pluginGroup>org.sonatype.plugins</pluginGroup>
    <pluginGroup>org.sonarsource.scanner.maven</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>UK</id>
      <name>UK Central</name>
      <url>http://uk.maven.org/maven2</url>
      <mirrorOf>central</mirrorOf>
    </mirror>
     --> 
    <!-- 
    官方仓库镜像:
    美国 http://repo.maven.apache.org/maven2
    英国 http://uk.maven.org/maven2 
    阿里云
        <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>
    -->

    <profile>
      <id>myShareProfile</id>
      
      <!-- 自定义多个仓库镜像-->      
      <repositories>
     
       <!-- 阿里云仓库 -->
       <repository>
          <id>alimaven</id>  
          <name>aliyun maven</name>  
          <url>https://maven.aliyun.com/repository/public</url>
           <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>

       <!-- maven 中心仓库-->
       <repository>
          <id>Centeral</id>
          <name>Central Maven2</name>
          <url>http://central.maven.org/maven2</url>
          <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository> 

       <!-- Maven 英国中心仓库-->
       <repository>
          <id>UK</id>
          <name>UK Central</name>
          <url>http://uk.maven.org/maven2</url>
          <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>
       
       <!--Spring 插件类库-->
        <repository>
          <id>SpringPlugin</id>
          <name>Spring Plugins</name>
          <url>http://mvnrepository.com/repos/sonatype-releases</url>
          <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>
       
        <!--Spring 类库-->
        <repository>
          <id>SpringLibs</id>
          <name>Spring Libs</name>
          <url>http://repo.spring.io/libs-milestone/</url>
          <snapshots><enabled>true</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>
       
         <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/libs-snapshot-local</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
       
        <repository>
          <id>Snoatype</id>
          <name>Snoatype</name>
          <url>http://mvnrepository.com/repos/sonatype-releases</url>
          <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>
       
         <repository>
          <id>Atlassian</id>
          <name>Atlassian Repository</name>
          <url>https://maven.atlassian.com/content/repositories/atlassian-public/</url>
          <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>
       
       <repository>
          <id>Hortonworks</id>
          <name>Hortonworks Repository</name>
          <url>http://repo.hortonworks.com/content/repositories/releases/</url>
          <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>
       
         <repository>
          <id>Jboss</id>
          <name>JBoss Releases Repository</name>
          <url>https://repository.jboss.org/nexus/content/repositories/releases/</url>
          <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>
       
        <repository>
          <id>Nexeo</id>
          <name>Nuxeo Releases Repository</name>
          <url>https://maven-eu.nuxeo.org/nexus/content/repositories/public-releases/</url>
          <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>
       
        <repository>
          <id>XWiki</id>
          <name>XWiki Releases Repository</name>
          <url>http://maven.xwiki.org/releases/</url>
          <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>
      
       <repository>
          <id>Apache</id>
          <name>Apache Releases Repository</name>
          <url>https://repository.apache.org/content/repositories/releases/</url>
          <snapshots><enabled>false</enabled></snapshots>  
          <releases><enabled>true</enabled></releases>  
       </repository>
               
     </repositories>
     
        <pluginRepositories>
        
                <pluginRepository>
                  <id>nexus-aliyun</id>
                  <url>http://maven.aliyun.com/nexus/content/groups/public</url>
                  <releases>
                    <enabled>true</enabled>
                  </releases>
                  <snapshots>
                    <enabled>true</enabled>
                  </snapshots>
                </pluginRepository>
          
                <pluginRepository>
                    <id>spring-snapshots</id>
                    <name>Spring Snapshots</name>
                    <url>https://repo.spring.io/libs-snapshot-local</url>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </pluginRepository>
        
                <pluginRepository>
                    <id>spring-milestones</id>
                    <name>Spring Milestones</name>
                    <url>https://repo.spring.io/libs-milestone-local</url>
                    <snapshots>
                        <enabled>false</enabled>
                    </snapshots>
                </pluginRepository>
        
        </pluginRepositories>

    </profile>
    
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
  <activeProfiles>
    <activeProfile>myShareProfile</activeProfile>
  </activeProfiles>
</settings>

0x03 Eclipse中的Maven使用

STS 是Spring官方团队出品的,最友好支持Spring的Eclipse衍生版本。

STS 下载地址:https://spring.io/tools
STS 已经继承了Maven插件,Maven并不执行任何具体的构件任务,所有这些任务都交给具体的插件来完成,例如:

  • 编译源代码是由maven-compile-plugin完成的。
  • 把Web 应用部署到tomcat 下是由tomcat-maven-plugin完成的,maven Tomcat 插件现在主要有两个版本,tomcat-maven-plugin和tomcat7-maven-plugin,使用方式基本相同。

STS 中配置Maven

配置安装目录

STS默认安装了一个版本的Maven,但是一般我们更换我们自己安装的。
image

配置用户设置

image

STS 中创建Maven Web项目

1.空白处右键 New-------> Other...
image
2.输入maven关键字,找到maven Project
image
3.进入New Maven Project界面
image
4.选择项目模板
Catalog下拉选择Internal,Filter 过滤器选择web,选中,然后Next
image
5.填写项目信息,然后点击Finish即可
image
6.修改JDK改变目录结构

完成后我们看到的目录结构会是这个样子的

image

因此我们需要修改下JDK,选中项目右键----Build Path----->Configure Build Path...

image

切换到library选项卡,选中图中所示的,点击Edit...

image

选择工作空间的JDK1.8

image

然后可以发现我们的项目结构已经发生改变了。

image
7.修改项目配置
切换到Navigator视图
image

然后可以看到

image

将原来的1.5 改成1.8
org.eclipse.jdt.core.prefs修改前

eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.processAnnotations=disabled
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.5

org.eclipse.jdt.core.prefs修改后

eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.processAnnotations=disabled
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8

8.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>com.xingyun</groupId>
  <artifactId>helloworld_web_maven_sample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>helloworld_web_maven_sample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
        <servlet.version>3.1.0</servlet.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <type>jar</type>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>helloapp</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <url>http://localhost:8080/manager/text</url>
                    <!-- server、username、password对应maven的setting下的配置 -->
                    <server>tomcat</server>
                    <username>admin</username>
                    <password>admin</password>
                    <path>/${project.build.finalName}</path>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

9.选中项目执行安装依赖

mvn install

当看到Build Success 说明成功
9.运行项目,命令执行后我们的项目就运行到tomcat7中了
选中项目右键-----Run As------>maven build...

tomcat7:run

image

10.然后打开浏览器访问网站即可

http://localhost:8080/helloapp/

image

附录一

感谢你耐心阅读本篇,最后送上一个神器命令,这个命令可帮助我们解决Maven依赖冲突.
使用场景,
比如A-1.2.jar 包依赖于 B-0.1.jar ,
然而项目中已经引入了一个较高版本B-1.1.jar,
我们想要的结果是只有A-1.2.jar 和B-1.1.jar
首先通过这个Maven照妖镜命令查找Maven依赖树

mvn dependency:tree

当执行成功后可以看到这个
image
其中,org.apache.ws.xmlschema 是 group id,
xmlschema-core: 是artifactId
jar: 指的压缩类型
2.2.1 指的是版本号

       <dependency>
            <groupId>xml-resolver</groupId>
            <artifactId>xml-resolver</artifactId>
            <version>1.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.ws.xmlschema</groupId>
                    <artifactId>xmlschema-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

exclusions的意思是移除自身传递的依赖jar包

附录二

再学一招,除了刚才的方法外,我们还可以指定全局统一版本的方法
这个配置的作用不会下载依赖,仅仅用来统一版本号

      <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>antlr</groupId>
                <artifactId>antlr</artifactId>
                <version>2.7.7</version>
            </dependency>
            </dependencies>
        </dependencyManagement>

附录三

配置项目本地私有包

 <dependency>
            <groupId>com.xingyun</groupId>
            <artifactId>test</artifactId>
            <version>1.0</version>
            <scope>system</scope>
                    <systemPath>${project.basedir}/src/main/resources/lib/test-1.0.jar</systemPath>
</dependency>

注:
${project.basedir}是Maven内置属性,

内置属性(Maven预定义,用户可以直接使用)

  • ${basedir} 表示项目根目录,即包含pom.xml文件的目录;
  • ${version} 表示项目版本;
  • ${project.basedir} 同${basedir};
  • ${project.baseUri} 表示项目文件地址;
  • ${maven.build.timestamp} 表示项目构件开始时间;
  • ${maven.build.timestamp.format} 表示属性${maven.build.timestamp}的展示格式,默认值为yyyyMMdd-HHmm,可自定义其格式,其类型可参考java.text.SimpleDateFormat。用法如下:
<properties>
<maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
</properties>

附录四

Maven 生命周期

validate,

initialize,

generate-sources,

process-sources,

generate-resources,

process-resources,

compile,

process-classes,

generate-test-sources,

process-test-sources,

generate-test-resources,

process-test-resources,

test-compile,

process-test-classes,

test,

prepare-package,

package,

pre-integration-test,

integration-test,

post-integration-test,

verify,

install,

deploy,

pre-clean,

clean,

post-clean,

pre-site,

site,

post-site,

site-deploy.

本篇完~

相关文章
|
7月前
|
Java 应用服务中间件 Maven
不同版本Idea部署Maven和Tomcat教学
不同版本Idea部署Maven和Tomcat教学
123 0
|
6月前
|
Java Maven
maven报错:[ERROR] 不再支持源选项 7。请使用 8 或更高版本。
maven报错:[ERROR] 不再支持源选项 7。请使用 8 或更高版本。
163 0
|
2月前
|
分布式计算 Java Scala
spark 与 scala 的对应版本查看、在idea中maven版本不要选择17,弄了好久,换成11就可以啦
spark 与 scala 的对应版本查看、.在idea中maven版本不要选择17,弄了好久,换成11就可以啦
93 2
|
4月前
|
缓存 Java Maven
Maven中的SNAPSHOT版本和正式版本
Maven中的SNAPSHOT版本和正式版本
|
4月前
|
Java Maven
Maven问题:【不支持源选项5。请使用7或更高版本。】问题解决方案
Maven问题:【不支持源选项5。请使用7或更高版本。】问题解决方案
82 0
|
6月前
|
Java 网络安全 Maven
16Maven - maven构建ssh项目(Eclipse版本)
16Maven - maven构建ssh项目(Eclipse版本)
43 0
|
6月前
|
IDE Java Maven
Maven - 使用maven-release-plugin规范化版本发布
Maven - 使用maven-release-plugin规范化版本发布
175 0
|
8月前
|
Java fastjson Maven
解决项目版本冲突——maven-shade插件使用
解决项目版本冲突——maven-shade插件使用
|
8月前
|
Dubbo JavaScript Java
Maven项目中的依赖出现版本冲突,最终发现是对Dependency Scope理解有误
本文记录一下遇到maven依赖版本冲突后的排查过程说明以及问题原因说明
66 0
|
8月前
|
Java Linux Maven
linux 安装 maven 3.8 版本
linux 安装 maven 3.8 版本
301 0