Maven

 ·  ☕ 7  · 👀...

官网

技术 特性 适用场景 说明
Maven 打包 - 官网
- Doc
- Guide to Working with Multiple Modules

安装

Windows

下载

https://maven.apache.org/download.cgi

解压

解压到d:\maven\

配置环境变量

环境变量名称 环境变量值
MAVEN_HOME D:\maven\
PATH D:\maven\bin;

检查

1
$ mvn -v

Mac brew 安装

1
2
3
4
5
6
$ brew search maven
$ brew install maven@3.5
$ mvn -v

# 卸载
$ brew uninstall maven@3.5

Mac 原始安装方法

下载

https://maven.apache.org/download.cgi

安装

解压到:/usr/local/maven

配置环境变量

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$ vim ~/.bash_profile
##### 内容如下 #####
# maven
export M2_HOME="/usr/local/maven"
export M2="$M2_HOME/bin"
export PATH="$M2:$PATH"
##### 内容结束 #####

$ source ~/.bash_profile

# 检查
$ mvn -v

CentOS7

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$ cd /usr/local
$ wget http://mirrors.tuna.tsinghua.edu.cn/apache/maven/maven-3/3.6.2/binaries/apache-maven-3.6.2-bin.tar.gz
$ tar zxvf apache-maven-3.6.2-bin.tar.gz
$ ln -s apache-maven-3.6.2 maven
$ vim /etc/profile
##### 增加如下内容 #####
export MAVEN_HOME=/usr/local/maven
export PATH=$PATH:$MAVEN_HOME/bin
##### 内容结束 #####

$ source /etc/profile
$ mvn -v

配置Maven

配置本地仓库路径

1
<localRepository>本地仓库路径</localRepository>

配置阿里云镜像仓库

1
$ vim /usr/local/maven/conf/settings.xml

增加如下内容:

1
2
3
4
5
6
<mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>central</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>

Maven 命令

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# 显示版本信息
$ mvn –version

# 清理项目生产的临时文件,一般是模块下的target目录
$ mvn clean

# 编译源代码,一般编译模块下的src/main/java目录
$ mvn compile

# 编译测试代码
$ mvn test-compile

# 只打jar包
$ mvn jar:jar

# 项目打包工具,会在模块下的target目录生成jar或war等文件
$ mvn package

# 测试命令,或执行src/test/java/下junit的测试用例
$ mvn test

# 将打包的jar/war文件复制到你的本地仓库中,供其他模块使用
$ mvn install

# 将打包的文件发布到远程仓库,提供其他人员进行下载依赖
$ mvn deploy

# 生成项目相关信息的网站
$ mvn site

# 将项目转化为Eclipse项目
$ mvn eclipse:eclipse

# 将项目转化为IDEA项目
$ mvn idea:idea

# 打印出项目的整个依赖树
$ mvn dependency:tree

# 创建Maven的普通java项目
$ mvn archetype:generate

# 编译测试的内容
$ mvn test-compile

# 在tomcat容器中运行web应用
$ mvn tomcat:run

# 调用 Jetty 插件的 Run 目标在 Jetty Servlet 容器中启动 web 应用
$ mvn jetty:run

# 清理并打包
$ mvn clean package

# 排除测试代码后进行打包
$ mvn clean package -Dmaven.test.skip=true

# 可以从本地存储库为您创建一个 archetype 目录
$ mvn archetype:crawl

Makefile示例

注意:命令必须以tab开头。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
client:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.ClientMain"

performance-client:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.PerformanceClientMain"

ssl-client:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.SslClientMain"

server:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.ServerMain"

ssl-server:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.SslServerMain"

slow-server:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.SlowServerMain"

simulator:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.SimulatorMain"

rebind:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.RebindMain"

parser:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.ParserMain"

dlr:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.DeliveryReceiptMain"

persist-client:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.persist.Main"

server-echo:
	mvn -e test-compile exec:java -Dexec.classpathScope="test" -Dexec.mainClass="com.cloudhopper.smpp.demo.ServerEchoMain"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$ make client
$ make server
$ make performance-client
$ make simulator
$ make rebind
$ make parser
$ make dlr
$ make ssl-client
$ make ssl-server
$ make persist-client
$ make server-echo

Maven插件

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<!-- 编译插件 -->
<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-compiler-plugin</artifactId>
   <version>3.6.1</version>
   <configuration>
       <source>1.8</source>
       <target>1.8</target>
   </configuration>
</plugin>

<!-- 用于配置JUnit -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19</version>
    <configuration>
        <testFailureIgnore>true</testFailureIgnore>  <!--测试有失败用例时,是否继续构建-->
     <skipTests>true</skipTests>                  <!--是否跳过测试阶段,方式1-->
      <skip>true</skip>                            <!--是否跳过测试阶段,方式2-->
    </configuration>
</plugin>
<!-- 运行时指定 -->
$ mvn package -DskipTests
$ mvn package -Dmaven.test.skip=true
$ mvn package -Dmaven.test.failure.ignore=true

<!-- 定制化打包 -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.5.5</version>
    <configuration>
        <archive>
            <manifest>
                <mainClass>org.struy.MainTets</mainClass>
            </manifest>
        </archive>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
    <executions>
        <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<!-- 执行本地脚本 -->
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.6.0</version>
    <executions>
        <execution>
            <id>build-docker-image</id>
            <phase>package</phase>
            <goals>
                <goal>exec</goal>
            </goals>
            <configuration>
                <executable>${basedir}/build.sh</executable>
            </configuration>
        </execution>
    </executions>
</plugin>
<!-- 构建docker镜像 -->
<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.10</version>
    <configuration>
        <imageName>docker.dapeng.example/hello-service:1.0-SNAPSHOT</imageName>
        <dockerDirectory>${basedir}/docker</dockerDirectory>
    </configuration>
    <executions>
        <execution>
            <id>build-image</id>
            <phase>package</phase>
            <goals>
                <goal>build</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<!-- jar指定目录,设定manifest的参数,或指定运行的Main class,还有依赖的jar包,加入classpath中 -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <outputDirectory>${project.build.directory}/${project.artifactId}/</outputDirectory>
    </configuration>
</plugin>
<!-- 复制依赖的jar包到指定的文件夹里 -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/${project.artifactId}/
                </outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>
                <excludeArtifactIds>dapeng-core</excludeArtifactIds>
            </configuration>
        </execution>
    </executions>
</plugin>
<!-- 用于一键部署,把本地打包的jar文件,上传到远程服务器上,并执行服务器上的shell命令 -->
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>wagon-maven-plugin</artifactId>
    <version>1.0</version>
    <configuration>
        <serverId>crawler</serverId>
        <fromDir>target</fromDir>
        <includes>*.jar,*.properties,*.sh</includes>
        <url>sftp://59.110.162.178/home/zhangxianhe</url>
        <commands>
            <command>chmod 755 /home/zhangxianhe/update.sh</command>
            <command>/home/zhangxianhe/update.sh</command>
        </commands>
        <displayCommandOutputs>true</displayCommandOutputs>
    </configuration>
</plugin>
<!-- 用于远程部署Java Web项目 -->
<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.2</version>
    <configuration>
        <url>http://59.110.162.178:8080/manager/text</url>
        <username>linjinbin</username>
        <password>linjinbin</password>
    </configuration>
</plugin>
<!-- 用于把多个jar包,打成1个jar包一般Java项目都会依赖其他第三方jar包,最终打包时,希望把其他jar包包含在一个jar包里 -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.4.3</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer
                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <manifestEntries>
                            <Main-Class>com.meiyou.topword.App</Main-Class>
                            <X-Compile-Source-JDK>${maven.compile.source}</X-Compile-Source-JDK>
                            <X-Compile-Target-JDK>${maven.compile.target}</X-Compile-Target-JDK>
                        </manifestEntries>
                    </transformer>
                </transformers>
            </configuration>
        </execution>
    </executions>
</plugin>
<!-- 获取git的commit-id插件,比如在打包jar包和构建docker镜像时用于区分版本(配合properties-maven-plugin 可使用${git.commit.id.abbrev}使用此变量在其他插件中获取commit-id) -->
<plugin>
    <groupId>pl.project13.maven</groupId>
    <artifactId>git-commit-id-plugin</artifactId>
    <version>2.2.1</version>
    <executions>
        <execution>
            <id>get-the-git-infos</id>
            <goals>
                <goal>revision</goal>
            </goals>
            <phase>package</phase>
        </execution>
    </executions>

    <configuration>
        <dotGitDirectory>${project.basedir}/.git</dotGitDirectory>

        <!-- @since 2.2.0 -->
        <dateFormatTimeZone>${user.timezone}</dateFormatTimeZone>

        <generateGitPropertiesFile>true</generateGitPropertiesFile>

        <generateGitPropertiesFilename>${project.build.directory}/git.ini</generateGitPropertiesFilename>

        <format>properties</format>

        <skipPoms>false</skipPoms>

        <injectAllReactorProjects>false</injectAllReactorProjects>
        <skip>false</skip>

        <!-- @since 2.1.12 -->
        <runOnlyOnce>false</runOnlyOnce>

        <!-- @since 2.1.9 -->
        <includeOnlyProperties>
            <includeOnlyProperty>^git.branch$</includeOnlyProperty>
            <includeOnlyProperty>^git.commit.id.abbrev$</includeOnlyProperty>
        </includeOnlyProperties>

        <useNativeGit>true</useNativeGit>

        <abbrevLength>7</abbrevLength>
        <commitIdGenerationMode>flat</commitIdGenerationMode>

        <gitDescribe>
            <skip>true</skip>
            <always>false</always>
            <abbrev>7</abbrev>
            <dirty>-dirty</dirty>
            <match>*</match>
            <forceLongFormat>false</forceLongFormat>
        </gitDescribe>
    </configuration>
</plugin>
<!-- 读取指定properties(这里是配合git-commit-id-plugin 以读取commit-id信息) -->
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>read-project-properties</goal>
            </goals>
            <configuration>
                <files>
                    <file>${project.build.directory}/git.ini</file>
                </files>
            </configuration>
        </execution>
    </executions>
</plugin>
<!-- 配置资源文件编码 -->
<plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <configuration>
        <encoding>UTF-8</encoding>    
    </configuration>
</plugin>
<!-- findbugs  静态java代码检查 -->
<reporting>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>2.3.1</version>
      </plugin>
    </plugins>
</reporting>
<!-- jetty服务器 -->
<plugin>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>maven-jetty-plugin</artifactId>
    <version>6.1.6</version>
    <configuration>
        <contextPath>/</contextPath>
        <scanIntervalSeconds>3</scanIntervalSeconds>
        <scanTargetPatterns>
            <scanTargetPattern>
                <directory>src/main/webapp/WEB-INF</directory>
                <excludes>
                    <exclude>**/*.jsp</exclude>
                </excludes>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </scanTargetPattern>
        </scanTargetPatterns>
        <requestLog implementation="org.mortbay.jetty.NCSARequestLog">
            <filename>target/yyyy_mm_dd.request.log</filename>
            <retainDays>90</retainDays>
            <append>true</append>
            <extended>false</extended>
            <logTimeZone>GMT</logTimeZone>
        </requestLog>
        <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                <port>80</port>
                <maxIdleTime>60000</maxIdleTime>
            </connector>
        </connectors>
    </configuration>
</plugin>
<!-- 生成java文档 -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
            <goals>
                <goal>javadoc</goal>
            </goals>
            <phase>compile</phase>
        </execution>
    </executions>
    <configuration>
        <encoding>UTF-8</encoding>
        <verbose>false</verbose>
        <show>public</show>
        <subpackages>com.pwrd.mobileqa.assist.resource</subpackages>
        <doclet>com.sun.jersey.wadl.resourcedoc.ResourceDoclet</doclet>
        <docletPath>${path.separator}${project.build.outputDirectory}</docletPath>
        <docletArtifacts> <!--解析项目生成javadoc需要的依赖-->
            <docletArtifact>
                <groupId>xerces</groupId>
                <artifactId>xercesImpl</artifactId>
                <version>2.6.1</version>
            </docletArtifact>
             ......
        </docletArtifacts>
        <!--  the following option is required as a work around for
                version 2.5 of the javadoc plugin which will be used
                by a maven version > 2.0.9-->
        <useStandardDocletOptions>false</useStandardDocletOptions>
        <additionalparam>-output ${project.build.outputDirectory}/resourcedoc.xml</additionalparam>
    </configuration>
</plugin>
<!-- 生成mybatis映射 -->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.0</version>
    <configuration>
        <verbose>true</verbose>
        <overwrite>true</overwrite>
    </configuration>
    <executions>
    <execution>
        <id>Generate MyBatis Artifacts</id>
        <goals>
        <goal>generate</goal>
        </goals>
    </execution>
    </executions>
</plugin>

配置 maven 多模块项目

父工程

  1. packaging 标签的文本内容必须为pom pom
  2. 必须删除 src 目录

子工程

1
2
3
4
5
6
<parent>
    <groupId>com.nxtele</groupId>
    <artifactId>base</artifactId>
    <version>1.0</version>
    <relativePath>../base/pom.xml</relativePath>
</parent>

打包

  • common、utils、dao、service、entity这三个模块的pom.xml文件中不需要build 内容,直接干掉

配置包扫描

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package com.wanglibing.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
//配置全局扫描
@ComponentScan(basePackages = "com.wanglibing")
//配置局部扫描
@MapperScan(basePackages = {"com.wanglibing.service.mapper"})
public class WebApplication {

	public static void main(String[] args) {
		SpringApplication.run(WebApplication.class, args);
	}

}

Maven Archetype模板开发

单模块

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# mapper-basic 是一个 maven项目
$ cd /Users/iamwlb/Documents/Workspace/java/mapper-basic
$ maven clean
# 从已有项目创建 archetype
$ mvn archetype:create-from-project
$ cd target/generated-sources/archetype
# 将打包的jar/war文件复制到你的本地仓库中,供其他模块使用
$ mvn install
# 生成archetype-catalog.xml
$ mvn archetype:crawl
# 测试(在列表中搜索最后一个条目)
$ mvn archetype:generate
# 从本地archeType模板中创建项目
$ mvn archetype:generate -DarchetypeCatalog=local
# 根据archeType模板创建项目maven命令示例
$ mvn archetype:generate -DgroupId=com.sample.test -DartifactId=test -Dversion=1.0.0-SNAPSHOT -DarchetypeGroupId=com.sample.archetypes -DarchetypeArtifactId=sample-archetype -DarchetypeVersion=1.0.0-SNAPSHOT -Dpackage=com.sample.test -DinteractiveMode=false

多模块

参考 Create an archetype from a multi-module project

1
2
3
4
$ mvn archetype:create-from-project -Darchetype.filteredExtensions=java
$ cd target/generated-sources/archetype/
$ mvn install
$ mvn archetype:generate -DarchetypeCatalog=local

删除 maven Archetype

1
2
$ vim /Users/iamwlb/.m2/repository/archetype-catalog.xml
##### 删除多余的 archetype #####

常见问题

-source 1.5中不支持diamond运算符

问题描述

-source 1.5 中不支持 diamond 运算符
[ERROR] (请使用 -source 7 或更高版本以启用 diamond 运算符)
[ERROR] -> [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/MojoFailureException

解决办法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
</build>

Maven无法使用ojdbc依赖

在 Oracle 官网下载需要的 JDBC 驱动,官网下载地址:http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html

1
2
# 将 Oracle JDBC 驱动包安装到 Maven 本地仓库
$ mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=11.2.0 -Dpackaging=jar -Dfile=ojdbc6.jar

pom.xml

1
2
3
4
5
<dependency>
   <groupId>com.oracle</groupId>
   <artifactId>ojdbc14</artifactId>
   <version>11.2.0</version>
</dependency>

参考


Wanglibing
Wanglibing
Engineer,Lifelong learner