文章目录
1. maven是什么?
它是一个软件开发的管理工具,主要管理的工作是:依赖管理,项目构建
groupId:一般用包名表示,表示项目是由哪个组织开发的 类似于籍贯
artifactId:一般是项目的名称 类似于姓名
version:该元素定义jar包的版本 类似于身份证号
maven优点:
1.依赖管理
2.一键构建
进入到想要构建的项目目录下的dos,输入mvn tomcat:run
2. maven安装
maven下载:https://pan.baidu.com/s/1zcLUvy7_D52u9CcJH-fT9w
下载之后,解压它,得到一个如下的目录结构:
配置 MAVEN_HOME ,变量值就是你的maven安装 的路径(bin目录之前一级目录)
将 %MAVEN_HOME%\bin 加入环境变量 path %MAVEN_HOME%\bin
通过 mvn -v命令检查 maven是否安装成功,看到maven的版本为3.3.9及java版本
3. 仓库配置
配置本地仓库
仓库下载:https://pan.baidu.com/s/1__zgM_VmJET4fu4jDkSUBw
maven安装路径下\conf\settings.xml文件中
配置<localRepository>/path/to/local/repo</localRepository>
改成自己的repository地址即可
maven找jar遵循什么顺序
优先查找本地仓库
本地找不到,则从私服上查找,找到后下载到本地仓库
私服上找不到,则从中央仓库查找,找到后下载到私服,最后下载到本地仓库
最终maven都会把jar下载到本地仓库,maven工程再引用本地仓库
4. maven目录结构
5.maven命令
5-1 clean
clean是maven工程的清理命令,执行 clean会删除target目录的内容。
5-2 compile
compile是maven工程的编译命令,作用是将src/main/java下的文件编译为class文件输出到target目录下。
cmd进入命令状态,执行mvn compile,如下图提示成功:
查看 target目录,class文件已生成,编译完成。
5-3 test
test是maven工程的测试命令,会执行src/test/java下的单元测试类。
cmd执行mvn test执行src/test/java下单元测试类,下图为测试结果,运行1个测试用例,全部成功。
5-4 package
package是maven工程的打包命令,对于java工程执行package打成jar包,对于web工程打成war包。
5-5 install
nstall是maven工程的安装命令,执行install将maven打成jar包或war包发布到本地仓库。
从运行结果中,可以看出:
当后面的命令执行时,前面的操作过程也都会自动执行
6. 使用eclipse开发maven项目
6-1 在eclipse中配置maven
点击window→preference
打开Maven Repositories窗口,右键选择rebuild Index
重构完如下所示
6-2 在eclipse中创建maven项目
- 在eclipse中创建一个maven工程
- 选择maven project
- 点next进入下面的界面
- 可以看到一个helloworld工程,但报错(添加下面的内容就OK了)
或者是右键选择项目,选择JavaEE Tools→Generate…
6-3 调整maven下jdk版本
- 右键项目选择Maven→Add Plugin
- 输入compile
- 在pom.xml文件的version下插入如下代码
<configuration>
<!-- 源码版本 -->
<source>1.7</source>
<!-- 编译版本 -->
<target>1.7</target>
<!-- 指定编码 -->
<encoding>utf-8</encoding>
</configuration>
4. 发现修改版本后报错,再次右键项目 选择Maven→Update Project
6-4 全局调整jdk版本
在maven的目录下conf下的setting.xm中,文件中找到有
<profile>
标签的地方,加上如下配置。
<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>
6-4 创建了Servlet但是报错
需要在pom.xml中添加依赖
- 点击eclipse下方的Dependencies选项
- 单击add,输入Servlet,选择后面为servlet-api的2.5版本
- 但是访问的时候报错
原因:刚才加入的依赖与tomcat原有的jar包发生了冲突,
或者是加入的时候直接选择provided即可
6-5 使用maven中的Tomcat进行发布
- 右键项目,选择Maven→Add Plugin,输入Tomcat7
- 在pom.xml中修改tomcat端口号等
<configuration>
<port>8081</port>
<!-- 项目路径 -->
<path>/helloWord</path>
<uriEncoding>utf-8</uriEncoding>
</configuration>
- 运行项目
6-6 作用范围
添加jar包的坐标时,还可以指定这个jar包将来的作用范围
compile 一般用于spring-core
test 一般用于Junit
provide一般用于servlet-api
runtime一般用于JDBC驱动