Maven学习笔记

来源:互联网 发布:西数移动硬盘在无网络 编辑:程序博客网 时间:2024/06/04 00:21

pom.xml基础配置: 
maven中,最让我迷惑的还是那一堆配置!

1、就拿这个属性配置来说: 

<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.sourceEncoding>UTF-8</project.reporting.sourceEncoding><java.version>1.7</java.version></properties>
我需要让整个项目统一字符集编码,就需要设定<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>;如果我需要让java编译版本统一,可以设置<java.version>1.7</java.version>当然maven不会那么乖乖的自动识别这些配置。但是像<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>和<project.reporting.sourceEncoding>UTF-8</project.reporting.sourceEncoding>默认还是可以识别的! 


2、Maven 二进制资源文件(pdf   swf    data...)部署出错,乱码的解决方案 。

Maven resources 插件会对文本资源文件进行转码,但是它无法区分文件是否是纯文本文件还是二进制文件。于是二进制文件在部署过程中也就被转码了,就无法正常打开了。官方文档建议按如下操作。例如不对这些文件进行转码。

<project> ... <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <configuration> ... <nonFilteredFileExtensions> <nonFilteredFileExtension>pdf</nonFilteredFileExtension> <nonFilteredFileExtension>swf</nonFilteredFileExtension> </nonFilteredFileExtensions> ...  </configuration>  </plugin> </plugins> ... </build> ... </project>

3、学习Maven之Maven Enforcer Plugin

在一个稍大一点的组织或团队中,你无法保证所有成员都熟悉Maven,那他们做一些比较愚蠢的事情就会变得很正常,例如给项目引入了外部的SNAPSHOT依赖而导致构建不稳定,使用了一个与大家不一致的Maven版本而经常抱怨构建出现诡异问题。maven-enforcer-plugin能够帮助你避免之类问题,它允许你创建一系列规则强制大家遵守,包括设定Java版本、设定Maven版本、禁止某些依赖、禁止SNAPSHOT依赖。只要在一个父POM配置规则,然后让大家继承,当规则遭到破坏的时候,Maven就会报错。除了标准的规则之外,你还可以扩展该插件,编写自己的规则。maven-enforcer-plugin的enforce目标负责检查规则,它默认绑定到生命周期的validate阶段。

在说这个插件是什么前我们先思考这么一个问题:当我们开发人员进入项目组进行开发前,要准备开发环境,而领导总是会强调工具的统一,编译环境的统一。比如要求所有开发人员使用JDK1.8进行开发。
开发人员接下来就是去下载指定版本的JDK,然后开始开发。但是如果开发人员的机器配置比较多,有好几个版本的JDK,而他虽然下载了JDK1.8,但是忘记配置环境变量,很有可能他用了JDK1.6进行的编译。
问题有了,该如何解决? Maven Enforcer plugin就是来解决这类问题。Enforcer可以在项目validate时,对项目环境进行检查。

Enforcer配置后默认会在validate后执行enforcer:enforce,然后对项目环境进行检查。拿上面对JDK的校验为例,我们在pom.xml中配置插件。

<?xml version="1.0" encoding="UTF-8"?><project>...    <build>        <plugins>            <plugin>                <artifactId>maven-enforcer-plugin</artifactId>                <version>1.4.1</version>                <executions>                    <execution>                        <id>default-cli</id>                        <goals>                            <goal>enforce</goal>                        </goals>                        <phase>validate</phase>                        <configuration>                            <rules>                                <requireJavaVersion>                                    <message>                                        <![CDATA[You are running an older version of Java. This application requires at least JDK ${java.version}.]]>                                    </message>                                    <version>[${java.version}.0,)</version>                                </requireJavaVersion>                            </rules>                        </configuration>                    </execution>                </executions>            </plugin>        </plugins>    </build>    <properties>        <java.version>1.8</java.version>    </properties> </project>
我本地配置没有JDK1.8,按照我的期望,执行maven命令时应该会失败。让我们来执行命令 mvn validate 会打出如下日志告知我们JDK版本过低。
qyfmac$ mvn validate[INFO] Scanning for projects...[INFO] ------------------------------------------------------------------------[INFO] Reactor Build Order:[INFO] [INFO] AppFuse Modular Application[INFO] AppFuse Modular Application - Core[INFO] AppFuse Modular Application - Web (Spring MVC)[INFO]                                                                         [INFO] ------------------------------------------------------------------------[INFO] Building AppFuse Modular Application 1.0-SNAPSHOT[INFO] ------------------------------------------------------------------------[INFO] [INFO] --- maven-enforcer-plugin:1.4.1:enforce (enforce-versions) @ stock ---[WARNING] Rule 1: org.apache.maven.plugins.enforcer.RequireJavaVersion failed with message:You are running an older version of Java. This application requires at least JDK 1.8.[INFO] ------------------------------------------------------------------------[INFO] Reactor Summary:[INFO] [INFO] AppFuse Modular Application ........................ FAILURE [  0.987 s][INFO] AppFuse Modular Application - Core ................. SKIPPED[INFO] AppFuse Modular Application - Web (Spring MVC) ..... SKIPPED[INFO] ------------------------------------------------------------------------[INFO] BUILD FAILURE[INFO] ------------------------------------------------------------------------[INFO] Total time: 1.886 s[INFO] Finished at: 2015-09-22T15:37:04+08:00[INFO] Final Memory: 16M/156M[INFO] ------------------------------------------------------------------------[ERROR] Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:1.4.1:enforce (enforce-versions) on project stock: Some Enforcer rules have failed. Look above for specific messages explaining why the rule failed. -> [Help 1][ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.[ERROR] Re-run Maven using the -X switch to enable full debug logging.[ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles:[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

其实执行命令 mvn enforcer:enforce 也可以达到上面的效果。区别就是validate是maven全局命令,enforcer:enforce是只执行这个插件的命令。
这里要注意一点,执行enforcer:enforce时,id必须是default-cli(具体原因请参阅:http://stackoverflow.com/questions/24827194/maven-enforcer-plugin-missing-or-invalid-rules),否则会报

he parameters 'rules' for goal org.apache.maven.plugins:maven-enforcer-plugin:1.4.1:enforce are missing or invalid

Maven Enforcer plugin标签详解
</pre><pre name="code" class="html"><plugin><artifactId>maven-enforcer-plugin</artifactId><version>1.4.1</version><executions>  <execution>    <id>default-cli</id>         --一个执行实例的id      <goals>        <goal>enforce</goal>     --执行的命令      </goals>      <phase>validate</phase>    --执行的阶段      <configuration>        <rules>                  --规则          <requireJavaVersion>   --JDK的版本            <message>            --失败后提示消息              <![CDATA[You are running an older version of Java. This application requires at least JDK ${java.version}.]]>             </message>             <version>[${java.version}.0,)</version>   --JDK版本规则           </requireJavaVersion>         </rules>       </configuration>    </execution>  </executions></plugin>
Enforcer的rules除了控制JDK版本,还有很多其他规则,甚至可以通过它的接口自定义。
alwaysFail - Always fail... used to test plugin configuration.
alwaysPass - Always passes... used to test plugin configuration.
banDistributionManagement - enforces that project doesn't have distributionManagement.
bannedDependencies - enforces that excluded dependencies aren't included.
bannedPlugins - enforces that specific plugins aren't included in the build.
bannedRepositories - enforces to not include banned repositories.
banTransitiveDependencies - enforces that project doesn't have transitive dependencies.
dependencyConvergence - ensure all dependencies converge to the same version.
evaluateBeanshell - evaluates a beanshell script.
reactorModuleConvergence - enforces that a multi module build follows best practice.
requireActiveProfile - enforces one or more active profiles.
requireEnvironmentVariable - enforces the existence of an environment variable
requireFilesDontExist - enforces that the list of files does not exist.
requireFilesExist - enforces that the list of files does exist.
requireFilesSize - enforces that the list of files exists and is within a certain size range.
requireJavaVersion - enforces the JDK version.
requireMavenVersion - enforces the Maven version.
requireNoRepositories - enforces to not include repositories.
requireOS - enforces the OS / CPU Architecture.
requirePluginVersions - enforces that all plugins have a specified version.
requirePrerequisite - enforces that prerequisites have been specified.
requireProperty - enforces the existence and values of properties.
requireReleaseDeps - enforces that no snapshots are included as dependencies.
requireReleaseVersion - enforces that the artifact is not a snapshot.
requireSameVersions - enforces that specific dependencies and/or plugins have the same version.
requireUpperBoundDeps - ensures that every (transitive) dependency is resolved to it's specified version or higher.

4、pluginManagement配置:

pluginManagement的作用类似于denpendencyManagement,只是denpendencyManagement是用于管理项目jar包依赖,pluginManagement是用于管理plugin。与pom build里的plugins区别是,这里的plugin(pluginManagement)是列出来,然后让子pom来决定是否引用。如果要让子模块继承父模块的plugin的使用,还是要在父模块里头声明这些plugin。

<build><pluginManagement><plugins><plugin><artifactId>maven-war-plugin</artifactId><version>2.5</version></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><source>${java.version}</source><target>${java.version}</target></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><version>2.6</version><configuration><nonFilteredFileExtensions><nonFilteredFileExtension>pdf</nonFilteredFileExtension><nonFilteredFileExtension>swf</nonFilteredFileExtension><nonFilteredFileExtension>data</nonFilteredFileExtension></nonFilteredFileExtensions></configuration></plugin><plugin><artifactId>maven-antrun-plugin</artifactId><version>1.3</version></plugin><plugin><artifactId>maven-assembly-plugin</artifactId><version>2.2-beta-5</version></plugin><plugin><artifactId>maven-dependency-plugin</artifactId><version>2.8</version></plugin><plugin><artifactId>maven-release-plugin</artifactId><version>2.3.2</version></plugin><plugin><artifactId>maven-clean-plugin</artifactId><version>2.5</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.4</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.12.4</version></plugin><plugin><artifactId>maven-jar-plugin</artifactId><version>2.5</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.7</version></plugin><plugin><artifactId>maven-site-plugin</artifactId><version>3.3</version></plugin></plugins></pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-enforcer-plugin</artifactId><version>1.4</version><executions><execution><id>enforce-no-snapshots</id><goals><goal>enforce</goal></goals><configuration><rules><requireReleaseDeps><onlyWhenRelease>true</onlyWhenRelease><message>No Snapshots Allowed!</message></requireReleaseDeps><!-- -Denforcer.skip=true --><!-- <requireReleaseVersion> --><!-- <message>No Snapshots Allowed!</message> --><!-- </requireReleaseVersion> --></rules><fail>true</fail></configuration></execution></executions></plugin></plugins><filters><filter>src/main/filters/filter-${env}.properties</filter></filters><resources><resource><directory>src/main/filters/resources/${env}</directory></resource><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build>
5、DependencyManagement和Dependencies
Maven 使用dependencyManagement 元素来提供了一种管理依赖版本号的方式。通常会在一个组织或者项目的最顶层的父POM 中看到dependencyManagement 元素。使用pom.xml 中的dependencyManagement 元素能让

所有在子项目中引用一个依赖而不用显式的列出版本号。Maven 会沿着父子层次向上走,直到找到一个拥有dependencyManagement 元素的项目,然后它就会使用在这个dependencyManagement 元素中指定的版本号。

例如在父项目里:

<dependencyManagement><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.2</version></dependency>...<dependencies></dependencyManagement>
然后在子项目里就可以添加mysql-connector时可以不指定版本号,例如:
<dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency></dependencies>
这样做的好处就是:如果有多个子项目都引用同一样依赖,则可以避免在每个使用的子项目里都声明一个版本号,这样当想升级或切换到另一个版本时,只需要在顶层父容器里更新,而不需要一个一个子项目的修改 ;另外如果某个子项目需要另外的一个版本,只需要声明version就可。
dependencyManagement里只是声明依赖,并不实现引入,因此子项目需要显式的声明需要用的依赖。

只有当 外层的dependencies 元素中没有指明版本信息时, dependencyManagement 中的 dependencies 元素才起作用。

相对于dependencyManagement,所有声明在dependencies里的依赖都会自动引入,并默认被所有的子项目继承。

0 0