Maven是什么
maven是一个基于Java的自动化构建工具。
maven最重要的功能是依赖管理和项目构建。
依赖管理
maven通过在pom.xml中使用dependencies标签来管理依赖。
<dependencies>
<dependency>
<groupId>net.oschina.j2cache</groupId>-->
<artifactId>j2cache-core</artifactId>
<version>2.7.7-release</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
groupId、artifactId、version确定一个唯一依赖的坐标。
scope表示maven依赖的范围
exclusion是排除的依赖
依赖传递
依赖A>依赖B>依赖C
依赖A间接依赖了依赖C,这样引入了依赖A也会间接引入依赖C。
另外可以使用exclusion 排除依赖
比如依赖A中不需要依赖C就可以使用exclusion标签。
<exclusion>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</exclusion>
maven仓库
maven仓库分为本地仓库和和远程仓库。
本地仓库一般在${user.home}/.m2/repository下,也可以通过修改/maven安装目录/conf/setting.xml修改
<localRepository></localRepository>
来自定义仓库目录。
远程仓库包括私服、中央仓库和其他公共仓库。
私服就是你搭建在局域网内的仓库只有局域网内的用户能访问。
中央仓库和其他公共仓库都是在公网上进行访问的仓库。
在pom.xml中使用如下配置来设置仓库
<repositories>
<repository>
<id>aliyun-repos</id> -->仓库id
<url>https://maven.aliyun.com/repository/public</url>-->仓库地址
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
因为maven是国外开发,maven的中央仓库也是在国外,使用中央仓库经常会出现网络问题。因此我们可以使用镜像来解决网络问题。
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
如上,这就是阿里云关于maven中央仓库的镜像。在maven安装目录/conf/setting.xml文件中配置。
依赖继承
项目之间是可以继承的,假设项目A和B,A如果继承了B,就可以使用B的依赖了。
<parent>
<groupId>org.jframework</groupId>
<artifactId>HCourt</artifactId>
<version>1.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
groupId、artifactId、version确定你要继承的项目的坐标。
relativePath是要继承的项目的相对路径
多模块项目构建
maven项目分为module和project
相同点:都是maven项目都有自己的pom.xml文件
不同点:project一般作为父项目不保留项目代码、module一般作为子项目。
使用多模块能力可以提升开发效率、降低项目耦合度、方便重用代码。
多模块项目实战
假设我们要开发一个电商系统(mall),我们需要一个父项目,一个启动项目的web模块,一个商品模块(commodity),一个用户模块(user),一个订单模块(order)。
创建父项目
这里选择Maven pom
然后就得到了一个没有任何代码的项目
创建子模块
这样就获得了所有的子模块。
另外web子模块作为启动模块还需要一个Application类作为项目启动入口。
先新建包和类
再继承类SpringBootServletInitializer然后编写main方法
一个多模块项目就OK了。