文章目录
1. 前言
现在基于java开发的项目越来越多,而我们在做项目时,不可避免的需要导入各种各样的jar包。如果每次建立一个项目到把相应的jar包拷贝到项目中会显得非常的繁琐。这时候,如何去管理我们的jar包就显得非常的重要。通过maven来管理存放jar包的仓库,会使得我们的开发效率大大提升。
【注意】:IDEA 2021 以及 之后自带Maven,可以直接使用。同时,也可以自己单独安装,本文就是讲述如何单独安装Maven并使用。
2. 下载安装与环境配置
2.1 下载与安装
-
在官网下载文件:https://maven.apache.org/download.cgi
下载后解压下面的压缩包到一个没有中文,空格的目录下如果嫌下载的慢,我这里有百度网盘链接:https://pan.baidu.com/s/1b4QWQnxDpNdxbX6Tl3B5fg
提取码:0fgk -
然后在电脑随便哪个地方建立一个文件夹,名字命名为:
repository
,作为maven的仓库。我这里是在D盘目录下建立的该文件,所以文件目录为:D:\software\Maven\repository
-
打开解压后的maven文件,在
D:\software\Maven\apache-maven-3.8.8\conf
文件夹下找到settings.xml
文件,打开此文件进行配置:-
添加本地仓库路径:(maven用来保存jar文件的目录)
-
添加阿里云的镜像,当你所填写的(G, A, V)坐标的jar包在本地仓库找不到时,他会根据坐标自动到这个地址下载,最终文件就下载到你的本地仓库了。
<mirror> <id>alimaven</id> <mirrorOf>central</mirrorOf> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/repositories/central/</url> </mirror>
-
配置全局JDK,即告诉maven用什么jdk去编译。
<profile> <id>jdk-1.8</id> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> </profile>
-
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. --> <!-- | 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.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 https://maven.apache.org/xsd/settings-1.2.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:\software\Maven\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> --> <!-- 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> <id>maven-default-http-blocker</id> <mirrorOf>external:http:*</mirrorOf> <name>Pseudo repository to mirror external repositories initially using HTTP.</name> <url>http://0.0.0.0/</url> <blocked>true</blocked> </mirror>--> <!-- 阿里云仓库 --> <mirror> <id>alimaven</id> <mirrorOf>central</mirrorOf> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/repositories/central/</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> <id>jdk-1.8</id> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> </profile> <!-- 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>
-
2.2 配置环境变量
最后,测试环境变量是否配置成功:打开cmd
,输入mvn -version
,出现如下界面说明配置成功
3. IEDA关联Maven(只需要配置一次)
-
打开IDEA,关闭项目:
-
点击全局设置:
-
在Settings窗口中配置maven解压后的文件夹路径,以及settings.xml路径
-
开启IDEA的快速自动编译功能(Settings和Default Settings都要配)
4. Maven使用
4.1 创建项目
(1) 创建项目
-
点击
New Project
创建项目:
-
给项目指定(g, a, v)含义:对于maven项目来说,坐标(G,A,V)就代表了一个依赖,到时候别人想导入我们自己的jar包时,如果我们发布到网上,别人也能根据(G,A,V)下载我们的jar包。
-
创建的项目如下:
-
查看项目中是否出现Maven标志
-
Maven常用的三个功能:
(2) 修改pom.xml文件
1个maven项目建好后,首先就要改写pom.xml,把它所依赖的所有jar都通过代码引入到项目中,通过G,A,V来引入外部jar包。如果不清楚一个依赖的G,A,V,可以去网上查查找网址:https://mvnrepository.com/,我们把GroupId或者artifactid的关键字输进去,就能查到了。
另一种方法:
也可以到仓库中查看(G, A, V)坐标,例如: E:\maven\repository\mysql\mysql-connector-java \5.1.20G:mysql 位于repository和A之间,可能有多级
A:mysql-connector-java --位于V的上一层,只有一级
V:5.1.20 --版本号,只有一级
以下文件配置都添加到 标签内:
-
在
<project></project>
标签内设置(G, A, V)坐标<groupId>com.hushi</groupId> <artifactId>couseSystem</artifactId> <version>1.0-SNAPSHOT</version>
-
在
<project></project>
标签内设置项目信息:<packaging>war</packaging> <!-- 项目打成什么包,默认是jar包,其他的比如war包 --> <name>couseSystem</name> <!-- 项目打包后名称 --> <description>内容分润</description> <!-- 项目描述信息 -->
-
在
<project></project>
标签内设置全局属性:<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <encoding>UTF-8</encoding> <spark-streaming-bigpipe.version>2.4.3.2-baidu</spark-streaming-bigpipe.version> <druid.version>1.2.6</druid.version> <scalatest.version>3.2.14</scalatest.version> </properties>
-
在
<project></project>
标签内进行多环境版本控制&属性控制
:<profiles> <!-- 环境3.2 --> <profile> <id>3.2</id> <properties> <scala.version>2.12.15</scala.version> <!-- scala版本控制,后续可通过${scala.version} 指定scala版本 --> <spark.version>3.2.2.3-baidu</spark.version> <!-- spark版本控制,后续可通过${spark.version} 指定scala版本 --> <scala.binary.version>2.12</scala.binary.version> <!-- scala.binary版本控制,后续可通过${scala.binary.version} 指定scala.binary版本 --> <package></package> </properties> </profile> <!-- 环境3.3 --> <profile> <id>3.3</id> <properties> <scala.version>2.12.15</scala.version> <!-- scala版本控制,后续可通过${scala.version} 指定scala版本 --> <spark.version>3.2.2.3-baidu</spark.version> <!-- spark版本控制,后续可通过${spark.version} 指定scala版本 --> <scala.binary.version>2.12</scala.binary.version> <!-- scala.binary版本控制,后续可通过${scala.binary.version} 指定scala.binary版本 --> </properties> </profile> </profiles>
-
在
<project></project >
标签内指定依赖的jar包(G,A,V)。<dependencies> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming_${scala.binary.version}</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-sql_${scala.binary.version}</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-hive_${scala.binary.version}</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-mllib_${scala.binary.version}</artifactId> <version>${spark.version}</version> <scope>provided</scope> </dependency> </dependencies>
注意:上面的添加jar包的代码中,多了
<scope>provided</scope>
是为了在打成架包的时候,不将该jar包打进去。 -
在
<project></project >
标签内添加插件,以及指定源文件夹。<!-- 设置插件 --> <build> <sourceDirectory>src/main/scala</sourceDirectory> <!-- 指定源文件夹 --> <testSourceDirectory>src/test/scala</testSourceDirectory> <!-- 指定测试文件夹 --> <plugins> <!-- 各个插件 --> <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <version>2.14.2</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> <configuration> <scalaVersion>${scala.version}</scalaVersion> <args> <arg>-target:jvm-1.7</arg> </args> </configuration> </plugin> </plugins> </build>
-
如果需要,可在
<project></project >
标签内指定远程仓库路径,即依赖jar包的拉取地:<repositories> <repository> <id>baidu-nexus</id> <url>https://maven.xxxxx/groups/public</url> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> </repository> <repository> <id>baidu-nexus-snapshot</id> <url>https://mavenxxxx/public-snapshots</url> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> </repository> </repositories>
-
如果有需要,可
<project></project >
标签内指定插件的下载地:<pluginRepositories> <pluginRepository> <id>baidu-nexus</id> <url>https://maven.xxxx.groups/public</url> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> </pluginRepository> </pluginRepositories>
-
一个完整的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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.baidu.content</groupId> <artifactId>ct_spark</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>jar</packaging> <name>ct-spark</name> <description>内容分润</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <encoding>UTF-8</encoding> <spark-streaming-bigpipe.version>2.4.3.2-baidu</spark-streaming-bigpipe.version> <druid.version>1.2.6</druid.version> <scalatest.version>3.2.14</scalatest.version> </properties> <profiles> <profile> <id>3.2</id> <properties> <scala.version>2.12.15</scala.version> <spark.version>3.2.2.3-baidu</spark.version> <scala.binary.version>2.12</scala.binary.version> <package></package> </properties> </profile> <profile> <id>3.3</id> <properties> <scala.version>2.12.15</scala.version> <spark.version>3.2.2.3-baidu</spark.version> <scala.binary.version>2.12</scala.binary.version> </properties> </profile> </profiles> <dependencies> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming_${scala.binary.version}</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-sql_${scala.binary.version}</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-hive_${scala.binary.version}</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-mllib_${scala.binary.version}</artifactId> <version>${spark.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <sourceDirectory>src/main/scala</sourceDirectory> <testSourceDirectory>src/test/scala</testSourceDirectory> <plugins> <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <version>2.14.2</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> <configuration> <scalaVersion>${scala.version}</scalaVersion> <args> <arg>-target:jvm-1.7</arg> </args> </configuration> </plugin> </plugins> </build> <!--ENV SETTINGS--> <repositories> <repository> <id>baidu-nexus</id> <url>https://maven.xxx/groups/public</url> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> </repository> <repository> <id>baidu-nexus-snapshot</id> <url>https://maven.xxx/xxx/groups/public-snapshots</url> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>baidu-nexus</id> <url>https://maven.xxx/groups/public</url> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> </pluginRepository> </pluginRepositories> </project>
4.2 项目打包并上传至服务器运行
-
点击右上角的package 或者
terminal
中使用mvn命令打包mvn -U clean package -P 3.3
其中:
-U
表示强制执行。
clean
表示Maven会删除target目录,也就是你的项目的构建目录,以确保从干净的状态开始构建。
package
表示Maven会把你的项目编译、测试并打包成一个可以分发的格式,比如一个JAR文件。
-P 3.3
表示多环境版本控制,使用id=3.3的环境。
进入到target目录下就可以看到相应的jar包:
-
把产生的war包拷贝到外部的tomcat服务器的webapps目录中
-
在tomcat的lib目录下找到start.bat文件,点击他就启动tomcat服务器,war包会自动解压变成一个目录
启动tomcat服务器后,浏览器中输入http://localhost/项目名,这里我是http://localhost/cs/index.html
结果如下:
4.3 在IDEA运行web项目
-
在pom.xml中添加Tomcat插件:
<!-- Tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <!-- 项目访问路径 --> <path>/cour</path> <!-- 访问项目的端口号 --> <port>80</port> </configuration> </plugin>
-
双击运行tomcat7插件的tomcat7:run
4.4 将外部的maven项目导入进来
5. Maven命令大全
1. 创建Maven的普通Java项目:
mvn archetype:create
-DgroupId=packageName
-DartifactId=projectName
2. 创建Maven的Web项目:
mvn archetype:create
-DgroupId=packageName
-DartifactId=webappName
-DarchetypeArtifactId=maven-archetype-webapp
3. 反向生成 maven 项目的骨架:
mvn archetype:generate
你是怎么创建你的maven项目的?是不是像这样:
mvn archetype:create -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId=com.ryanote -Dartifact=common
如果你还再用的话,那你就out了,现代人都用mvn archetype:generate了,它将创建项目这件枯燥的事更加人性化,你再也不需要记那么多的archetypeArtifactId,你只需输入archetype:generate,剩下的就是做”选择题”了.
cmd步骤:
缩写写法:
mvn archetype:generate -DgroupId=otowa.user.dao -DartifactId=user-dao -Dversion=0.01-SNAPSHOT
4. 编译源代码:
mvn compile
5. 编译测试代码:
mvn test-compile
6. 运行测试:
mvn test
7. 产生site:
mvn site
8. 打包:
mvn package
9. 在本地Repository中安装jar:
mvn install
例:installing D:\xxx\xx.jar to D:\xx\xxxx
10. 清除产生的项目:
mvn clean
11. 生成eclipse项目:
mvn eclipse:eclipse
12. 生成idea项目:
mvn idea:idea
13. 组合使用goal命令,如只打包不测试:
mvn -Dtest package
14. 编译测试的内容:
mvn test-compile
15. 只打jar包:
mvn jar:jar
16. 只测试而不编译,也不测试编译:
mvn test -skipping compile -skipping test-compile
( -skipping 的灵活运用,当然也可以用于其他组合命令)
17. 清除eclipse的一些系统设置:
mvn eclipse:clean
18.查看当前项目已被解析的依赖:
mvn dependency:list
19.上传到私服:
mvn deploy
20. 强制检查更新,由于快照版本的更新策略(一天更新几次、隔段时间更新一次)存在,如果想强制更新就会用到此命令:
mvn clean install-U
21. 源码打包:
mvn source:jar
或
mvn source:jar-no-fork
mvn compile与mvn install、mvn deploy的区别
1. mvn compile,编译类文件
2. mvn install,包含mvn compile,mvn package,然后上传到本地仓库
3. mvn deploy,包含mvn install,然后,上传到私服