Maven

还没有maven的时候,我们在项目添加依赖包的时候,需要自己下载添加到lib,但在项目中引入的依赖包其又依赖别的依赖包,并且可能存在版本冲突的问题。

一、认识maven

解决复杂依赖传递问题,打包项目

  • 约定优于配置
  • 简单易用
  • 支持测试
  • 插件丰富

二、安装和配置

  • MVN_HOME
  • 配置setting.xml


    加载配置的顺序
1、阿里镜像
  
  alimaven  
  aliyun maven  
   http://maven.aliyun.com/nexus/content/groups/public/  
  central          
 
2、profies可以配置开发、测试、生产不同环境时的配置
image.png

三、maven项目结构

image.png

1、pom.xml

(1)、groupId 域名反过来
(2)、artfactId 功能命名
(3)、version 版本号
  • 主版本号.次版本号.增量版本号-<里程碑版本>
  • mvn clean package -U (每次上线版本release强制从远端仓库重新拉一次)
(4)、packaging 打包方式 默认是jar
(5)、dependencyManagement

a)、只能出现在父pom
b)、统一版本号
c)、声明 (子POM里用到再引)
dependencies即使在子项目中不写该依赖项,那么子项目仍然会从父项目中继承该依赖项(全部继承)
dependencyManagement里只是声明依赖,并不实现引入,因此子项目需要显示的声明需要用的依赖。如果不在子项目中声明依赖,是不会从父项目中继承下来的;只有在子项目中写了该依赖项,并且没有指定具体版本,才会从父项目中继承该项,并且version和scope都读取自父pom;另外如果子项目中指定了版本号,那么会使用子项目中指定的jar版本。

(6)、dependency
  • Type 默认jar
  • scope 定义依赖包在什么时候,并且会不会在打包上(优化pom文件)
    a)compile 编译 (默认)
    b)test 测试
    c)provided 例如 tomcat已经提供servlet的依赖包,这个依赖在编译时就不会被打包上
    d)runtime运行时 例如JDBC驱动实现在运行时才会用到,编译时不会用到。
    e)system 本地一些jar 在maven中央仓库没有的依赖包,例如短信jar
  • 依赖传递
    第一列表示直接依赖的scope,第一行表示间接依赖的scope


    image.png
  • 依赖仲裁
    a)、最短路径原则
    b)、加载先后原则,当最短路径相等时,则是按书写顺序的先后


    image.png
  • exclusions
    排除包 例如spring内引用common-logging,在项目并不会用来,可用来排除这个依赖包。

四、生命周期

image.png

五、常用命令

  • compile
  • clean 删除target/ 生成的包
  • test test case junit/testNG
  • package 打包
  • install 把项目install到local repo
  • deploy 发本地jar发布到remote

六、实现plugin

七、搭建私服

  • a)、下载nexus http://books.sonatype.com/nexus-book/reference3/index.html
  • b)、安装启动
    http://127.0.0.1:8081
    nexus.exe /run
    admin/admin123
  • c)、发布pom.xml 配置

    
        xiaoyuan-nexus-release
        Nexus Release Repository
        http://localhost:8081/repository/maven-releases/
    
    
        xiaoyuan-nexus-snapshot
        Nexus Snapshot Repository
        http://localhost:8081/repository/maven-snapshots/
    

  • d)、setting.xml配置

    
        xiaoyuan-nexus-release
        admin
        admin123
    
    
        xiaoyuan-nexus-snapshot
        admin
        admin123
    

八、自定义archetype(脚手架)

  • 生成一个archetype
    a)、mvn archetype:create-from-project
    b)、cd /target/generated-sources/archetype
    c)、mvn install
  • 从archetype创建项目 mvn archetype:generate -DarchetypeCatalog=local

九、实现dev、test、pro不同环境下的配置

  • 不同环境下的配置文件


    image.png
  • pom.xml配置

    
        dev
        
            dev
        
        
            true
        
    
    
        test
        
            test
        
    
    
        pro
        
            pro
        
    



    
        
            ${basedir}/src/main/resources
                
                    conf/**
                
        
        
            src/main/resources/conf/${profiles.active}
        
    

  • 在打包时则使用 mvn clean package -P pro,生成对应的配置文件


    image.png

你可能感兴趣的:(Maven)