为什么要用maven
因为 开发的过程中需要很多的jar文件,需要手工从网络中获得,
然后东西太多了,需要管理 和下载
所以采用maven 来管理
maven 可以做什么:
- 管理jar文件
- 自动下载jar和他的文档
- 管理你需要的jar版本
- 帮你编译程序
- 帮你打包文件
操作
- 清理
- 编译
- 测试
- 报告
- 打包
maven核心概念
- POM : 项目对象模型
- 约定的目录结构:maven 项目的目录和文件的位置是规定的
- 坐标 : 是一个唯一的字符串,是用来表示资源的
- 依赖管理: 管理你的项目
- 仓库管理
- 生命周期
- 插件和目标
- 继承
- 聚合
安装maven
- 下载,配置环境 变量
- 修改 本地仓库(可以提前把下载好的仓库替代进去)(需要修改默认仓库位置,下载国内源位置)
POM
- 坐标
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>
<!-- 公司或者组织的唯一标志,并且配置时生成的路径也是由此生成, 如com.companyname.project-group,maven会将该项目打成的jar包放本地路径:/com/companyname/project-group -->
<groupId>com.companyname.project-group</groupId>
<!-- 项目的唯一ID,一个groupId下面可能多个项目,就是靠artifactId来区分的 -->
<artifactId>project</artifactId>
<!-- 版本号 -->
<version>1.0</version>
</project>
- 依赖:dependencies 相当于java中的import
就是你的项目中要是用的各种资源的说明
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>compile</scope>
</dependency>
</dependencies>
maven 约定的目录结构
hellow
----/src
--------/main # 放主程序java代码和配置文件
-------------/java # 你的程序包和包中的java文件
-------------/resources # java程序中所需要的配置文件
--------/test #放测试程序和文件
----/pom.xml #maven的核心文件
例子:
操作 mvn compile 编译main/java中的所有java文件
maven的生命周期
就是maven构建项目的过程:清理,编译,测试,报告,打包 ,安装, 部署
但是maven的执行过程是通过插件来完成的:
单元测试 (junit)
maven借助junit,批量测试你类中的大量方法是否符合预期
单元测试使用方法:
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
插件的配置:
<!-- 编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
继承
parent
版本管理
版本管理:
ctrl+alt+V
依赖管理
依赖管理:(子项目不需要全部的父类插件,所以采用依赖管理dependcymanagement)
//引入 依赖管理
<dependencyManagement>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<optional>true</optional>
</dependency>
</dependencyManagement>
后续子项目中不需要制定版本号
独立管理
直接在子项目中添加 所需要的版本号(系统会有就近原则)
排除依赖
exclusion
<exclusions>
<exclusion>
<groupId>jline</groupId>
<artifactId>jline</artifactId>
</exclusion>
</exclusions>
聚合
modules