`
maimode
  • 浏览: 411999 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

maven入门学习及环境搭建

阅读更多

本文将简单介绍maven及使用命令,重点介绍如何搭建maven开发环境,最后给出一个利用maven创建项目的例子。

 

一 maven是什么

 

简单的说,maven是项目构建和依赖管理的工具。

 

利用maven可以脱离IDE创建、编译,打包、发布项目。类似产品如ant。

 

二 快速了解

 

Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information.

 

 

At first glance Maven can appear to be many things, but in a nutshell Maven is an attempt to apply patterns to a project's build infrastructure in order to promote comprehension and productivity by providing a clear path in the use of best practices. Maven is essentially a project management and comprehension tool and as such provides a way to help with managing:

  • Builds
  • Documentation
  • Reporting
  • Dependencies
  • SCMs
  • Releases
  • Distribution

 

链接:http://maven.apache.org/users/index.html

 

三 下载安装

 

以下安装测试是在window7,Eclipse Java EE IDE for Web Developers Version: Helios Service Release 2(3.6)上进行的。

 

A 在系统中安装maven工具(环境)

 

安装maven之前确保已经配置好了JDK环境(jre不行,必须是jdk环境)。

下载地址:http://labs.mop.com/apache-mirror/maven/binaries/apache-maven-3.0.4-bin.zip

 

window上安装配置如下,其他操作系统详见http://maven.apache.org/download.html#Installation

 

1.下载后解压到任意位置,如:D:\dev\apache-maven-3.0.4

2.配置环境变量,在用户变量中增加:

 

key:M2_HOME value如: D:\dev\apache-maven-3.0.4

key:M2 value:%M2_HOME%\bin

key:MAVEN_OPTS value如: -Xms256m -Xmx512m (此属性值可选)

key:Path value:%M2% (添加或更新)

 

然后检查JAVA_HOME属性是否配置的为jdk的环境,而且Path中是否配置了 %JAVA_HOME%\bin 值,配置完毕后,在控制台中运行如下命令:

 mvn --version

如果打印版本信息则说明安装成功。

 

maven使用本地库来存放项目所需的jar包,安装完毕maven后maven会将${user.home}/.m2/repository/位置作为默认本地库位置。安装完后最好自己重新配置本地库位置,配置方法如下:

${user.home}/.m2/目录下增加settings.xml文件,内如如下:

 

<?xml version="1.0" encoding="UTF-8"?>

<settings>
  <localRepository>c:/repository</localRepository>
</settings>

  其中c:/repository就是自定义的本地库位置。

 

B 安装eclipse插件m2eclipse:

eclipse更新地址:http://download.eclipse.org/technology/m2e/releases

(离线link安装包超过10M未能上传至附件中)

 

安装成功插件后在项目向导也会有maven的向导:

 

 

安装完插件后重启eclipse可能会提示: Eclipse is running in a JRE, but a JDK is required

Some Maven plugins may not work when importing projects or updating source folders.错误。

因为maven需要使用JDK而不是jre,所以需要修改两个位置对jdk的引用:

1. 修改installed JREs,把默认jre改为JDK路径

2. 修改eclipse运行环境应用的jre:在eclipse.ini文件中增加如下参数

-vm

C:\Program Files (x86)\Java\jdk1.6.0_14\bin\javaw.exe

 

然后重启eclipse应该就不再提示jre的问题了。

 

安装完m2eclipse插件最好配置一下:

 

http://hzbook.group.iteye.com/group/wiki/2872-Maven-in-action 写道
无论是Eclipse还是NetBeans,当我们集成Maven时,都会安装上一个内嵌的Maven,这个内嵌的Maven通常会比较新,但不一定很稳定,而且往往也会和我们在命令行使用的Maven不是同一个版本。这里有会出现两个潜在的问题:首先,较新版本的Maven存在很多不稳定因素,容易造成一些难以理解的问题;其次,除了IDE,我们也经常还会使用命令行的Maven,如果版本不一致,容易造成构建行为的不一致,这是我们所不希望看到的。因此,我们应该在IDE中配置Maven插件时使用与命令行一致的Maven。
在m2eclipse环境中,点击菜单栏中的Windows,然后选择Preferences,在弹出的对话框中,展开左边的Maven项,选择Installation子项,在右边的面板中,我们能够看到有一个默认的Embedded Maven安装被选中了,点击Add…然后选择我们的Maven安装目录M2_HOME,添加完毕之后选择这一个外部的Maven

 

  修改如图所示:

 

 

四 常用

 

其实没有eclipse插件我们照样也可以使用maven来创建和管理项目,但只是不太那么方便,有了插件与IDE集成,就免去在控制台中输入繁琐命令的麻烦。

 

快速使用示例:

 

下面介绍在控制台命令行中使用maven来创建项目的示例。

 

1.创建工程

 

在windows命令行中,首先进入某个文件夹下(这个文件即作为工作空间了),如D:\pro,然后输入下面的命令在这个位置创建一个名称为my-app的项目。

 

 

mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

 

 

 

上面的步骤创建项目结构如下:

 

my-app
|-- pom.xml
`-- src
    |-- main
    |   `-- java
    |       `-- com
    |           `-- mycompany
    |               `-- app
    |                   `-- App.java
    `-- test
        `-- java
            `-- com
                `-- mycompany
                    `-- app
                        `-- AppTest.java

 

 

2. 编写java文件

 

进入项目目录,D:\pro\my-app\src\main\java\com\mycompany\app下有个示例java文件App.java

 

如果自己编写java文件就放在\src\main\java下;

如果是资源文件如属性配置文件放在\src\main\resources下,编译或打包时这个位置等同于\src\main\java;

测试文件存放位置:\src\test

 

3. 编译项目

 

在命令行中输入如下命令:

 

 

mvn compile
 

 

 

4. 测试项目

 

在命令行中输入如下命令

 

 

mvn test

 

 

 

5. 项目打包

 

在命令行中输入如下命令即可将项目打包,maven会根据不同的项目类型将项目打为不同的包,如jar,war等。打包前会先对项目进行一次编译、测试,然后才打包。

 

 

mvn package

 

 

 

6. 运行项目或将项目包发布到库中

 

打包后的项目可以来运行或者安装到本地库中以便其他项目引用。

 

运行此示例项目:

 

 

java -cp target/my-app-1.0-SNAPSHOT.jar com.mycompany.app.App

 

 

 

将项目包安装到本地库中,同样执行安装过程也会先执行编译、测试、打包、最后才将包复制到本地库中。

 

 

mvn install
 

 

 

 

至此,一个简单maven使用入门教程学习完毕。在eclipse中使用maven开发项目的方法估计可以类比命令行中的使用过程。

 

至于更加详细具体的如何使用maven来工作,自己可以从网上去查阅资料,学习别人的最佳实践经验,也可以自己取探索,以后我再慢慢补充。

 

 

 

 

下面引用maven官方对maven常用命令的介绍

 

Running Maven Tools

Maven Phases

Although hardly a comprehensive list, these are the most common default lifecycle phases executed.

  • validate: validate the project is correct and all necessary information is available
  • compile: compile the source code of the project
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

There are two other Maven lifecycles of note beyond the default list above. They are

  • clean: cleans up artifacts created by prior builds
  • site: generates site documentation for this project

Phases are actually mapped to underlying goals. The specific goals executed per phase is dependant upon the packaging type of the project. For example, package executes jar:jar if the project type is a JAR, and war:war is the project type is - you guessed it - a WAR.

An interesting thing to note is that phases and goals may be executed in sequence.

mvn clean dependency:copy-dependencies package

This command will clean the project, copy dependencies, and package the project (executing all phases up to package, of course).

 

一个简单的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">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-app</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Maven Quick Start Archetype</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
 

 

 

This is a very simple POM but still displays the key elements every POM contains, so let's walk through each of them to familiarize you with the POM essentials:

  • project This is the top-level element in all Maven pom.xml files.
  • modelVersion This element indicates what version of the object model this POM is using. The version of the model itself changes very infrequently but it is mandatory in order to ensure stability of use if and when the Maven developers deem it necessary to change the model.
  • groupId This element indicates the unique identifier of the organization or group that created the project. The groupId is one of the key identifiers of a project and is typically based on the fully qualified domain name of your organization. For example org.apache.maven.plugins is the designated groupId for all Maven plug-ins.
  • artifactId This element indicates the unique base name of the primary artifact being generated by this project. The primary artifact for a project is typically a JAR file. Secondary artifacts like source bundles also use the artifactId as part of their final name. A typical artifact produced by Maven would have the form <artifactId>-<version>.<extension> (for example, myapp-1.0.jar).
  • packaging This element indicates the package type to be used by this artifact (e.g. JAR, WAR, EAR, etc.). This not only means if the artifact produced is JAR, WAR, or EAR but can also indicate a specific lifecycle to use as part of the build process. (The lifecycle is a topic we will deal with further on in the guide. For now, just keep in mind that the indicated packaging of a project can play a part in customizing the build lifecycle.) The default value for the packaging element is JAR so you do not have to specify this for most projects.
  • version This element indicates the version of the artifact generated by the project. Maven goes a long way to help you with version management and you will often see the SNAPSHOTdesignator in a version, which indicates that a project is in a state of development. We will discuss the use of snapshots and how they work further on in this guide.
  • name This element indicates the display name used for the project. This is often used in Maven's generated documentation.
  • url This element indicates where the project's site can be found. This is often used in Maven's generated documentation.
  • description This element provides a basic description of your project. This is often used in Maven's generated documentation.

 

 

How do I compile my application sources?

Change to the directory where pom.xml is created by archetype:generate and execute the following command to compile your application sources:

mvn compile

 

 

How do I compile my test sources and run my unit tests?

Now you're successfully compiling your application's sources and now you've got some unit tests that you want to compile and execute (because every programmer always writes and executes their unit tests *nudge nudge wink wink*).

Execute the following command:

mvn test

 

 

How do I create a JAR and install it in my local repository?

Making a JAR file is straight forward enough and can be accomplished by executing the following command:

mvn package

If you take a look at the POM for your project you will notice the packaging element is set to jar. This is how Maven knows to produce a JAR file from the above command (we'll talk more about this later). You can now take a look in the ${basedir}/target directory and you will see the generated JAR file.

Now you'll want to install the artifact you've generated (the JAR file) in your local repository (~/.m2/repository is the default location). For more information on repositories you can refer to our Introduction to Repositories but let's move on to installing our artifact! To do so execute the following command:

mvn install

 

 

There are plenty of other standalone goals that can be executed as well, for example:

mvn clean

This will remove the target directory with all the build data before starting so that it is fresh.

Perhaps you'd like to generate an IntelliJ IDEA descriptor for the project?

mvn idea:idea

This can be run over the top of a previous IDEA project - it will update the settings rather than starting fresh.

If you are using Eclipse IDE, just call:

mvn eclipse:eclipse

 

 

How do I add resources to my JAR?

Another common use case that can be satisfied which requires no changes to the POM that we have above is packaging resources in the JAR file. For this common task, Maven again relies on the Standard Directory Layout, which means by using standard Maven conventions you can package resources within JARs simply by placing those resources in a standard directory structure.

You see below in our example we have added the directory ${basedir}/src/main/resources into which we place any resources we wish to package in our JAR. The simple rule employed by Maven is this: any directories or files placed within the ${basedir}/src/main/resources directory are packaged in your JAR with the exact same structure starting at the base of the JAR.

 

 

How do I build other types of projects?

Note that the lifecycle applies to any project type. For example, back in the base directory we can create a simple web application:

mvn archetype:generate \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-webapp \
    -DgroupId=com.mycompany.app \
    -DartifactId=my-webapp

Note that these must all be on a single line. This will create a directory called my-webapp containing the following project descriptor:

<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">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany.app</groupId>
  <artifactId>my-webapp</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>my-webapp</finalName>
  </build>
</project>

 

 

 

 

  • 大小: 98 KB
  • 大小: 50 KB
  • 大小: 74.4 KB
  • 大小: 207.3 KB
  • 大小: 76.2 KB
  • 大小: 182 KB
  • 大小: 177.2 KB
  • 大小: 8.1 KB
  • 大小: 192.2 KB
1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics