maven构建的一些小技巧

maven从设计上来说非常的简单,但是却是一个非常强大的工具。很多人将maven只是当做一个构建工具(从源代码生成可运行软件),但是实际上可以将maven当做一个项目管理工具,比如工程管理、插件管理、Jar包依赖管理、软件发布仓库管理等。

下面讲解一些在使用maven当中所遇到的一些小的技巧。

maven是如何判断操作系统的?

操作系统家族是通过Maven Enforcer Plugin来实现的,具体来说,和如下代码的效果是完全一致的:

Family is calculated based on testing against the name string retreived from the JDK. The name, arch and version values are retreived from the JDK using the following code:

1
2
3
public static final String OS_NAME = System.getProperty( "os.name" ).toLowerCase( Locale.US );
public static final String OS_ARCH = System.getProperty( "os.arch" ).toLowerCase( Locale.US );
public static final String OS_VERSION = System.getProperty( "os.version" ).toLowerCase( Locale.US );

profiles可以配置哪些POM节点?

内置在POM文件中,这样是比较推荐的方式,这样不会造成工程在迁移的时候造成信息丢失。
可以修改如下的节点:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<repositories>
<pluginRepositories>
<dependencies>
<plugins>
<properties> (not actually available in the main POM, but used behind the scenes)
<modules>
<reporting>
<dependencyManagement>
<distributionManagement>
a subset of the <build> element, which consists of:
<defaultGoal>
<resources>
<testResources>
<finalName>

POM elements outside

这样做的方式是不允许的,对工程迁移、编译都非常的不友好。可以通过外部文件比如settings.xml profiles.xml来一些参数,但是相对来说,危害要稍微小一些。

如何配置仓库镜像(MirrorOf)?

在POM文件中使用Repositories标签就可以从你希望的地址上去下载构件,比如依赖库或者插件。这样对于工程的迁移性比较好。在任何地方都可以构建起来。

但是有的时候,你希望在不修改工程POM文件的情况下使用另外不同的仓库,这个时候就可以使用mirror。关于mirrorOf的规则可以参考官方文档[1]

几个需要注意的地方:
1、最快的镜像应该放在最前面
2、如果第一个镜像的规则是*,那么后面的仓库可能不会使用。
3、的默认值是central

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<mirrors>
<mirror>
<id>aliyun</id>
<mirrorOf>central</mirrorOf>
<name>阿里云公共仓库</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</mirror>

<mirror>
<id>repo2</id>
<mirrorOf>!central,*</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://repo2.maven.org/maven2/</url>
</mirror>
</mirrors>

  1. 1.Apache maven 配置仓库镜像:http://maven.apache.org/guides/mini/guide-mirror-settings.html