【开发工具】Maven——基本使用

Maven——基本作用

仓库机制:为了提高代码的复用性,我们往往将jar包拆成不同的包,供给其他项目去复用代码(即使是微服务也要抽离一个common包,将不同服务之间需要共同用到工具类、实体类复用),所以maven出现了,除了在本地开发中提供这样的包和包之间依赖关系的管理,同样maven还设立了远程仓库的概念,对于一些开发贡献值,可以将代码发布到远程仓库让各种开发者去使用这个依赖包,maven在这一块有着完善的生态体系;
编译代码:maven会手动调用java编译器完成java文件到classes的文件的转换,这中间需要处理很多协调性的东西都是maven帮忙完成的
依赖冲突:以前手动做jar包管理的时候,往往可能在同一个包下出现了类名相同的classes文件,maven会处理整个问题

项目的构建

从本地资源到打包资源
从本地java文件到class文件
从松散文件结构到规范文件结构
管理项目相关的其他内容,比如开发者信息,版本等等

在这里插入图片描述

在这里插入图片描述

统一管理jar包

在开发中经常需要依赖第三方的包,包与包之间存在依赖关系,版本间还有兼容性问题,有时还里要将旧的包升级或降级,当项目复杂到一定程度时包管理变得非常重要。
仅仅通过jar包的几个属性,就能确定唯一的jar包,在指定的文件pom.xml中,只要写入这些依赖属性,就会自动下载并管理jar包。
(jar最后会进入lib文件目录)

Maven——仓库机制

在这里插入图片描述

利用groupID+AfricatlID+version确定依赖所在

基本仓库概念

我们只需要知道顺序,然后以及怎么配置
依赖查找:本地仓库——中央仓库——远程仓库
Ps
本地仓库:m2文件夹下的依赖
中央仓库:所有网民共享
远程仓库:自己建立的私服

中央仓库配置

在maven根目录找到conf文件夹,然后编辑setting.xml

<mirrors>
    <mirror>
      <id>alimaven</id>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf>        
    </mirror>
</mirrors>

引入中央仓库

<repositories>  
        <repository>  
            <id>alimaven</id>  
            <name>aliyun maven</name>  
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
            <releases>  
                <enabled>true</enabled>  
            </releases>  
            <snapshots>  
                <enabled>false</enabled>  
            </snapshots>  
        </repository>  
</repositories>

远程仓库配置

在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">
   <!--…………-->
   <repositories>
      <repository>
         <id>companyname.lib1</id>
         <url>http://download.companyname.org/maven2/lib1</url>
      </repository>
      <repository>
         <id>companyname.lib2</id>
         <url>http://download.companyname.org/maven2/lib2</url>
      </repository>
   </repositories>
</project>

Maven——构建过程

在这里插入图片描述

validate(校验)	校验项目是否正确并且所有必要的信息可以完成项目的构建过程。
initialize(初始化)	初始化构建状态,比如设置属性值。
sources	
	generate-sources(生成源代码)	生成包含在编译阶段中的任何源代码。
	process-sources(处理源代码)	处理源代码,比如说,过滤任意值。
resources
	generate-resources(生成资源文件)	生成将会包含在项目包中的资源文件。
	process-resources (处理资源文件)	复制和处理资源到目标目录,为打包阶段最好准备。
compile(编译)	编译项目的源代码。
process-classes(处理类文件)	处理编译生成的文件,比如说对Java class文件做字节码改善优化。


test-sources(
	generate-test-sources(生成测试源代码)	生成包含在编译阶段中的任何测试源代码。
	process-test-sources(处理测试源代码)	处理测试源代码,比如说,过滤任意值。
test-resources
	generate-test-resources(生成测试资源文件)	为测试创建资源文件。
	process-test-resources(处理测试资源文件)	复制和处理测试资源到目标目录。
test-compile(编译测试源码)	编译测试源代码到测试目标目录.
process-test-classes(处理测试类文件)	处理测试源码编译生成的文件。


package
	test(测试)	使用合适的单元测试框架运行测试(Juint是其中之一)。
	prepare-package(准备打包)	在实际打包之前,执行任何的必要的操作为打包做准备。
	package(打包)	将编译后的代码打包成可分发格式的文件,比如JAR、WAR或者EAR文件。
integration
	pre-integration-test(集成测试前)	在执行集成测试前进行必要的动作。比如说,搭建需要的环境。
	integration-test(集成测试)	处理和部署项目到可以运行集成测试环境中。
	post-integration-test(集成测试后)	在执行集成测试完成后进行必要的动作。比如说,清理集成测试环境。


verify (验证)	运行任意的检查来验证项目包有效且达到质量标准。
install(安装)	安装项目包到本地仓库,这样项目包可以用作其他本地项目的依赖。
deploy(部署)	将最终的项目包复制到远程仓库中与其他开发者和项目共享。

Maven——聚合方式

依赖聚合

通过dependencies标签,按照依赖的查找顺序进行查找;

注意,如果是本地package的话,一定要记得重新install子包的依赖,不然可能会报编译错误

<?xml version="1.0" encoding="UTF-8"?>
<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">
   <dependencies>
        <dependency>
            <groupId>com.jm</groupId>
            <artifactId>jm-public-common_service</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.jm</groupId>
            <artifactId>jm-public-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

父子聚合

父工程的一切依赖配置被子工程复制一份,也可以重写

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <parent>
        <groupId>com.jm</groupId>
        <artifactId>jm-root</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
         <!-- 
           默认:../pom.xmlMaven首先在构建当前项目的地方寻找父项 
           设置: 其次在文件系统的这个位置(relativePath位置)
           仓库:然后在本地仓库,
           远程:最后在远程仓库寻找父项目的pom
         -->
    </parent>
</project>

Maven——配置语法

基本描述

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion><!-- POM版本的版本约束  -->
    <groupId>asia.banseon</groupId><!-- 全球组织的唯一标识 -->
    <artifactId>banseon-maven2 </artifactId><!--组织内工程文件的唯一标识  -->
    <packaging>jar</packaging><!-- 文件类型,与插件对应 -->
    <version>1.0-SNAPSHOT</version><!-- 版本 -->
    <name>banseon-maven</name><!-- 项目的名称, Maven产生的文档用 -->
    <url>http://www.baidu.com/banseon</url><!-- 项目主页的URL, Maven产生的文档用 -->
    <description>A maven project to study maven.  </description><!--  项目的详细描述, Maven 产生的文档用   -->
    <prerequisites> <!-- 描述了这个项目构建环境中的前提条件 .  -->
        <maven>2.0.3</maven><!-- 构建该项目或使用该插件所需要的Maven的最低版本 -->
    </prerequisites>
</project>

环境语法

用于更复杂的一些pom配置的管理

声明环境

<profiles>
    <profile>
         <!--激活条件(1)被activeProfiles指定了这个id-->
        <id>alwaysActiveProfile</id>
         <!--激活条件(2)更复杂的判断-->
        <activation>
            <activeByDefault></activeByDefault><!-- profile默认是否激活的标志 -->
            <jdk></jdk><!-- jdk限制  -->
            <os><!-- OS限制 -->
                <name>Windows 7</name>
                <family>Windows</family>
                <arch>x64</arch>
                <version>7.2.3580</version>
            </os>
            <property><!--存在就激活-->
                <name>mavenVersion</name><!-- 激活profile的属性的名称 -->
                <value>2.0.3</value><!-- 激活profile的属性的值 -->
            </property>
            <file><!--文件检测限制-->
                <exists>/usr/local/xbz/workspace/</exists><!-- 如果指定的文件存在 , 则激活profile .  -->
                <missing>/usr/local/xbz/workspace/</missing><!-- 如果指定的文件不存在 , 则激活profile .  -->
            </file>
        </activation>
        
      <!--环境被激活后,嵌套中的所有标签则有效果-->
       <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.3.2</version>
        </dependency>
    </dependencies>
    </profile>
</profiles>

激活环境

<activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
</activeProfiles>

变量管理

定义变量

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <developer.organization><![CDATA[xy公司]]></developer.organization>
    <spring.version>1.2.6</spring.version>
</properties>

使用变量

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
</dependency>

内置变量

${basedir} 项目根目录
${project.build.directory} 构建目录,缺省为target
${project.build.outputDirectory} 构建过程输出目录,缺省为target/classes
${project.build.finalName} 产出物名称,缺省为${project.artifactId}-${project.version}
${project.packaging} 打包类型,缺省为jar
${project.xxx} 当前pom文件的任意节点的内容
${settings.localRepository} settings文件
${user.home} java

依赖管理

<dependencies>
    <dependency>
        <groupId>org.apache.maven</groupId><!-- 依赖的group ID -->
        <artifactId>maven-artifact</artifactId><!-- 依赖的artifact ID -->
        <version>3.8.1</version><!-- 依赖的版本号 .  在Maven 2里, 也可以配置成版本号的范围 .  -->
        <type>jar</type><!--  依赖类型 , 默认类型是jar . 它通常表示依赖的文件的扩展名 , 但也有例外 . 一个类型可以被映射成另外一个扩展名或分类器 . 类型经常和使用的打包方式对应 ,  尽管这也有例外 . 一些类型的例子:jar , war , ejb-client和test-jar . 如果设置extensions为 true , 就可以在 plugin里定义新的类型 . 所以前面的类型的例子不完整 .  -->
        <scope>test</scope><!-- 依赖范围 . 在项目发布过程中 , 帮助决定哪些构件被包括进来 . 欲知详情请参考依赖机制 . 
              - compile :默认范围 , 用于编译
              - provided:类似于编译 , 但支持你期待jdk或者容器提供 , 类似于classpath
              - runtime: 在执行时需要使用
              - test:    用于test任务时使用
              - system: 需要外在提供相应的元素 . 通过systemPath来取得
              - systemPath: 仅用于范围为system . 提供相应的路径
              - optional:   当项目自身被依赖时 , 标注依赖是否传递 . 用于连续依赖时使用 -->
        <!-- 当计算传递依赖时 ,  从依赖构件列表里 , 列出被排除的依赖构件集 . 即告诉maven你只依赖指定的项目 , 不依赖项目的依赖 . 此元素主要用于解决版本冲突问题 -->
        <exclusions>
            <exclusion>
                <artifactId>spring-core</artifactId>
                <groupId>org.springframework</groupId>
            </exclusion>
        </exclusions>
        <optional>true</optional><!-- 可选依赖 , 如果你在项目B中把C依赖声明为可选 , 你就需要在依赖于B的项目(例如项目A)中显式的引用对C的依赖 . 可选依赖阻断依赖的传递性 .  -->
    </dependency>
</dependencies>

构建管理

<!--构建项目需要的信息 -->
<build>
        <!--【1】文件和目录配置 -->

        <directory /><!--构建产生的所有文件存放的目录 -->
        <finalName /><!--产生的构件的文件名,默认值是${artifactId}-${version}。 -->
        <filters /><!--当filtering开关打开时,使用到的过滤器属性文件列表 -->
     
        <!--该元素设置了项目源码目录,当构建项目的时候,构建系统会编译目录里的源码。该路径是相对于pom.xml的相对路径。 -->
        <sourceDirectory />
        <!--该元素设置了项目脚本源码目录,该目录和源码目录不同:绝大多数情况下,该目录下的内容 会被拷贝到输出目录(因为脚本是被解释的,而不是被编译的)。 -->
        <scriptSourceDirectory />
        <!--该元素设置了项目单元测试使用的源码目录,当测试项目的时候,构建系统会编译目录里的源码。该路径是相对于pom.xml的相对路径。 -->
        <testSourceDirectory />
        <!--被编译过的应用程序class文件存放的目录。 -->
        <outputDirectory />
        <!--被编译过的测试class文件存放的目录。 -->
        <testOutputDirectory />

         

        <!--【2】扩展配置
        		使用来自该项目的一系列构建扩展 
        -->
        <extensions>
            <!--描述使用到的构建扩展。 -->
            <extension>
                <!--构建扩展的groupId -->
                <groupId />
                <!--构建扩展的artifactId -->
                <artifactId />
                <!--构建扩展的版本 -->
                <version />
            </extension>
        </extensions>

        <!--
         【3】常规资源管理
        这个元素描述了项目相关的所有资源路径列表,
        例如和项目相关的属性文件,这些资源被包含在最终的打包文件里。 -->
        <resources>
            <!--这个元素描述了项目相关或测试相关的所有资源路径 -->
            <resource>
                <!-- 描述了资源的目标路径。该路径相对target/classes目录(例如${project.build.outputDirectory})。举个例 
                    子,如果你想资源在特定的包里(org.apache.maven.messages),你就必须该元素设置为org/apache/maven /messages。然而,如果你只是想把资源放到源码目录结构里,就不需要该配置。 -->
                <targetPath />
                <!--是否使用参数值代替参数名。参数值取自properties元素或者文件里配置的属性,文件在filters元素里列出。 -->
                <filtering />
                <!--描述存放资源的目录,该路径相对POM路径 -->
                <directory />
                <!--包含的模式列表,例如**/*.xml. -->
                <includes />
                <!--排除的模式列表,例如**/*.xml -->
                <excludes />
            </resource>
        </resources>
        <!--
          【4】测试资源管理
      这个元素描述了单元测试相关的所有资源路径,例如和单元测试相关的属性文件。 -->
        <testResources>
            <!--这个元素描述了测试相关的所有资源路径,参见build/resources/resource元素的说明 -->
            <testResource>
                <targetPath />
                <filtering />
                <directory />
                <includes />
                <excludes />
            </testResource>
        </testResources>


         <!--【5】插件配置 -->
        <!--使用的插件列表 -->
        <plugins>
            <!--参见build/pluginManagement/plugins/plugin元素 -->
            <plugin>
                <groupId />
                <artifactId />
                <version />
                <extensions />
                <executions>
                    <execution>
                        <id />
                        <phase />
                        <goals />
                        <inherited />
                        <configuration />
                    </execution>
                </executions>
                <dependencies>
                    <!--参见dependencies/dependency元素 -->
                    <dependency>
                        ......
                    </dependency>
                </dependencies>
                <goals />
                <inherited />
                <configuration />
            </plugin>
        </plugins>
    </build>

构建主要是调用maven插件完成一系类的生命周期

约束管理

父类中声明

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

子类中引用

)1,不需要指定版本号和作用域,直接引用父类的
)2,如果指定了,那就会子类被重写

<dependencies>
   <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
   </dependency>
</dependencies>

插件的约束

 <!--子项目可以引用的默认插件信息。该插件配置项直到被引用时才会被解析或绑定到生命周期。给定插件的任何本地配置都会覆盖这里的配置 -->
<build>
        <pluginManagement>
            <plugins>
                <!--plugin元素包含描述插件所需要的信息。 -->
                <plugin>
                    <groupId /> <!--插件在仓库里的group ID -->
                    <artifactId /><!--插件在仓库里的artifact ID -->
                    <!--被使用的插件的版本(或版本范围) -->
                    <version />
                    <!--是否从该插件下载Maven扩展(例如打包和类型处理器),由于性能原因,只有在真需要下载时,该元素才被设置成enabled。 -->
                    <extensions />
                    <!--在构建生命周期中执行一组目标的配置。每个目标可能有不同的配置。 -->
                    <executions>
                        <!--execution元素包含了插件执行需要的信息 -->
                        <execution>
                            <!--执行目标的标识符,用于标识构建过程中的目标,或者匹配继承过程中需要合并的执行目标 -->
                            <id />
                            <!--绑定了目标的构建生命周期阶段,如果省略,目标会被绑定到源数据里配置的默认阶段 -->
                            <phase />
                            <!--配置的执行目标 -->
                            <goals />
                            <!--配置是否被传播到子POM -->
                            <inherited />
                            <!--作为DOM对象的配置 -->
                            <configuration />
                        </execution>
                    </executions>
                    <!--项目引入插件所需要的额外依赖 -->
                    <dependencies>
                        <!--参见dependencies/dependency元素 -->
                        <dependency>
                            ......
                        </dependency>
                    </dependencies>
                    <!--任何配置是否被传播到子项目 -->
                    <inherited />
                    <!--作为DOM对象的配置 -->
                    <configuration />
                </plugin>
            </plugins>
        </pluginManagement>
</build>

Maven——环境搭建

windows

linux

idea

idea注意事项

Maven——插件举例

插件开发请关注maven插件系列

主要是基于一定的业务需要,要干预或者增强打包的功能所运用的插件;
<plugins>
    <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>applicationContext.xml</exclude>
                    <exclude>properties/**</exclude>
                    <exclude>log4j.properties</exclude>
                </excludes>
            </configuration>
    </plugin>
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>tomcat-maven-plugin</artifactId>
        <version>1.1</version>
        <configuration>
            <path>/wp</path>
            <port>8080</port>
            <uriEncoding>UTF-8</uriEncoding>
            <url>http://localhost:8080/manager/html</url>
            <server>tomcat6</server>
        </configuration>
    </plugin>
    <!--
        maven-war-plugin
    项目如果是web主应用,我们可以使用maven-war-plugin来对webapps下各类文件进行过滤。用法参考maven-resources-plugin
    -->
    <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <warName>demo-Rest</warName>
                <webResources>
                    <resource>
                        <directory>src/main/webapp/WEB-INF</directory>
                        <filtering>true</filtering>
                        <targetPath>WEB-INF</targetPath>
                        <includes>
                            <include>web.xml</include>
                        </includes>
                    </resource>
                </webResources>
            </configuration>
    </plugin>
    <!--properties-maven-plugin
        多部署环境中的配置分离
    -->
    <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>properties-maven-plugin</artifactId>
            <version>1.0.0</version>
            <configuration>
                <files>
                    <file>profiles/${runtime.env}/jdbc.properties</file>
                    <file>profiles/${runtime.env}/redis.properties</file>
                    <file>profiles/${runtime.env}/batch.properties</file>
                    <file>profiles/${runtime.env}/config.properties</file>
                </files>
            </configuration>
            <executions>
                <execution>
                    <phase>initialize</phase>
                    <goals>
                        <goal>read-project-properties</goal>
                    </goals>
                </execution>
            </executions>
    </plugin>
</plugins>```


版权声明:本文为weixin_44275259原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。