[reproduced] maven learning (on) - basic introductory usage

1. Download and install

1.1  Download maven 3.1.1

First go to the official website http://maven.apache.org/download.cgi to  download the latest version (currently 3.1.1  ), after the download is complete, extract it to a directory (in this article it is C:\Java\maven-3.1.1 )

 

2.1  Configure environment variables

In the system environment variable, add MAVEN_HOME (or M2_HOME) whose value is C:\Java\maven-3.1.1, and then append " ;%MAVEN_HOME%\bin " to the PATH environment variable.

Detection method:

a) Re-enter the command line (DOS window) mode, enter echo %MAVEN_HOME% If it can display C:\Java\maven-3.1.1, it means that the environment variable is working

b) Enter mvn -version, the version number of maven and jdk will be displayed under normal circumstances

(Premise: The jdk environment must be installed first, otherwise the project cannot be compiled normally later)

 

Understanding " Warehouse "

After running mvn -version for the first time, a .m2 directory will be created in the user directory (for example: C:\Users\current user name\.m2\), this directory is maven's "local warehouse", and the warehouse is in maven an important concept.

Imagine that we will create many projects at the same time at work, and each project may reference some common jar packages (dll files in .NET). One way is to copy a copy of these dependent jars in each project. package (or dll file), this is obviously not good, the same file is saved in multiple copies on the hard disk, which takes up too much space, and the versions of these dependent jar packages (or dll files) are not easy to manage (such as a common The jar package is upgraded from 1.0 to 2.0. If all projects that reference this jar package need to be updated, they must be modified one by one).

The maven warehouse solves these problems very well. It creates a local warehouse on each machine, and manages the jar packages that all the maven projects on the machine depend on, and these jar packages are uniquely identified by " coordinates " (Note: Coordinates are another important concept, which will be discussed later. Here, as long as it is simply understood as an identifier that " uniquely identifies a jar package file name and version number "), so that all maven projects do not need to be like Copy the jar package to the lib directory as before, and the whole maven project looks very clean.

 

Configure a proxy server (optional)

In the process of compiling, testing and packaging the maven project, you will need to download jar packages and other files from the maven central repository (ie: a site published by the maven organization on the Internet, which has included most of the current mainstream jar packages). To use a proxy server to access the Internet, you need to configure a proxy server.

Copy a copy of %MAVEN_HOME%\conf\settings.xml to the local warehouse C:\Users\current username\.m2\, then edit the file and find the following paragraph

copy code
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>
copy code

把注释去掉,host这里填写代理服务器的地址(可以用IP)以及port端口,如果需要用户名/密码认证,则填写username/password节点,否则username/password这二个节点去掉,nonProxyHosts表示某些地址不需要经过代理服务器,多个地址之间用|分隔,支持通配符,比如172.156.* 

 

二、创建项目“骨架”

下面用命名行创建一个最基本的maven项目

2.1 mvn archetype:generate

先创建项目的根目录,比如c:\test,命令行窗口下输入

cd /d c:\test

mvn archetype:generate

首次运行时,mvn会从远程"中央仓库"下载一些必需的文件到"本地仓库" - (如果你有兴趣,可以在等待下载过程中,观察一下"C:\Users\当前用户名\.m2\repository"到底下载了些啥东东)

下载完成后(下一篇会讲解如何,在局域网环境中搭建“私服”,直接从局域网的代理仓库中下载这些依赖项),会自动进入交互模式,会让你输入一些基本信息,类似下面这样:

...

[INFO] Generating project in Interactive mode (这里会卡一会儿,因为要联网获取项目模板)
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
1: remote -> br.com.ingenieux:elasticbeanstalk-service-webapp-archetype (A Maven Archetype Encompassing RestAssured, Jetty, Jackson, Guice and Jersey for Publishing JAX-RS-based Services on AWS' Elastic Beanstalk Service)
... (这里会自动列出很多项目模板,每种模板前面会有一个数字序号)

336: remote -> org.apache.maven.archetypes:maven-archetype-quickstart (An archetype which contains a sample Maven project.)

...

Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 336: (这里根据每个人机器上安装的eclipse插件不同,可能默认的数字不是这个,先不管,直接回车)

Choose org.apache.maven.archetypes:maven-archetype-quickstart version: 
1: 1.0-alpha-1
2: 1.0-alpha-2
3: 1.0-alpha-3
4: 1.0-alpha-4
5: 1.0
6: 1.1
Choose a number: 6: (直接回车)
Define value for property 'groupId': : cnblogs (可暂时先理解成类似package或namespace的名称,通常我们填写组织机构名称缩写)
Define value for property 'artifactId': : maven-hello-world (组件名称,可暂时理解成项目名称)
Define value for property 'version':  1.0-SNAPSHOT: : (版本号,直接回车,默认1.0-SNAPSHOT)
Define value for property 'package':  cnblogs: : (打包后的jar文件名,相当于.net中项目最后生成的程序集dll名称)
Confirm properties configuration:
groupId: cnblogs
artifactId: maven-hello-world
version: 1.0-SNAPSHOT
package: cnblogs
 Y: :  (直接回车确认)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.1
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: cnblogs
[INFO] Parameter: packageName, Value: cnblogs
[INFO] Parameter: package, Value: cnblogs
[INFO] Parameter: artifactId, Value: maven-hello-world
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS (看到这个,表示项目创建成功!)
[INFO] ------------------------------------------------------------------------
...

 

2.2 maven项目的目录结构

C:\test\maven-hello-world>tree
Folder PATH listing for volume win7
Volume serial number is AA2C-6E70
C:.
├───src
│   ├───main
│   │   └───java
│   │       └───cnblogs
│   └───test
│       └───java
│           └───cnblogs
└───target
    └───classes
        └───cnblogs

注意上面带红色的目录名,maven项目采用“约定优于配置”的原则,src/main/java约定用于存放源代码,src/main/test用于存放单元测试代码,src/target用于存放编译、打包后的输出文件。这是全世界maven项目的通用约定,请记住这些固定的目录结构。

 

三、编译项目

先进入刚才创建项目的根目录

cd /d c:\test\maven-hello-world

然后执行 mvn clean compile

这样就能对项目进行编译了,编译后会自动在target目录中生成class文件,如果编译成功,会输出类似下面的信息

yangjunmingmatoMacBook-Pro-7:maven-hello-world jimmy$ mvn clean compile
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building maven-hello-world 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ maven-hello-world ---
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ maven-hello-world ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/jimmy/Desktop/study/maven-hello-world/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ maven-hello-world ---
[INFO] Compiling 1 source file to /Users/jimmy/Desktop/study/maven-hello-world/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.515s
[INFO] Finished at: Wed Jan 01 19:08:32 CST 2014
[INFO] Final Memory: 10M/156M
[INFO] ------------------------------------------------------------------------

 

四、单元测试

mvn clean test

这样就能做单元测试了,so easy !

如果单元测试不通过,会提示出错信息,注意看输出。

注:从输出上可以发现,test前,会先执行compile,即先编译,再执行单元测试.

有兴趣的朋友,可以修改下/src/test/java/cnblogs/AppTest.java里的内容,把testApp()方法中的assertTrue( true );改成assertTrue( false );再跑下单元测试,看下有什么不同

 

五、项目打包

通常我们会把java项目打包成jar包或war包,maven中打包的命令为

mvn clean package

运行完后,会在target目录下生成jar包

注:从输出 可以发现,package前,会先执行compile,再执行test,最后才是package打包

 

六、项目运行

该项目中的App.java中有main方法,可以直接运行,常规方式下,我们如果想直接运行class文件,得敲一段很长的命令,maven中不必这么复杂,先用记事本打开项目根目录下的pom.xml文件,增加下面这节内容:

  View Code

上述这段内容插入在</project>之前即可。

然后在命令行下,输入

mvn exec:exec

即可直接运行,下面是输出:

C:\test\maven-hello-world>mvn exec:exec
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building maven-hello-world 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.2.1:exec (default-cli) @ maven-hello-world ---
Hello World!
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.175s
[INFO] Finished at: Mon Jan 13 22:35:02 CST 2014
[INFO] Final Memory: 6M/111M
[INFO] ------------------------------------------------------------------------

 

七、项目部署

如果是web项目,使用命令

mvn clean jboss-as:deploy

就能自动将web项目部署到jboss中(前提是jboss web server已经成功启动),因为刚才我们创建的是一个最基本的maven项目,并非web项目,所以执行这条命令,应该会失败,后面会讲如何在eclipse中用插件部署web项目,这里可以先跳过。

另外:

有时候,我们的项目是一个类库,只是封装一些方法供其它项目引用,对于这种项目,我们可以用 mvn clean install 把生成的jar包,安装到“本地仓库”中,这样本机其它项目需要使用该jar包时,只要在pom里配置依赖项即可,不用把jar包复制到当前项目中。

 

八、eclipse中集成maven

8.1 修改eclipse中使用的maven版本

eclipse自带了maven3.0.4,如果想使用最新的3.1.1,可以在eclipse -> window -> perferences -> Maven -> Installations 里参考下图设置一下

 

8.2 安装Red Hat JBoss Developer Studio(可选,纯个人喜欢)

eclipse -> help -> Eclipse Marketplace 搜索jboss,找到Red Hat JBoss Developer Studio,安装即可

 

8.3 创建一个web的maven示例项目

File -> New -> Maven Project -> Next ,在接下来的窗口中会看到一大堆的项目模板,Filter栏里输入“jboss-javaee6-webapp-archetype”,参考下图

然后Next,在接下来的界面中填写groupId之类

然后Finish完成项目创建。整个过程其实跟前面提到的纯手式命令行完全类似,只不过借助于插件,以图形化的方式更友好而已,直接Finish

项目上右击->Run As 就能看到很多Maven的选项,顾名思义,如何选择Maven install,等效于命令行执行mvn clean install,其它几项的含义一看便知,一般来讲Maven test 和 Maven install这二个基本上已经够用,如果还想定义自己的命令,比如 maven clean package,可以选择“6 Maven build...”,会弹出一个界面,如下图,在name输入框填写名称:maven-web-sample-package(名字可以随便写,只要方便自己记忆就行),Goals栏输入clean package

最后点击Run关闭这个窗口,以后可以直接从工具栏调出这个选择,如下图:

实际使用中,发现eclipse与maven之间并非整合得天衣无缝,有时候eclipse中项目图标经常会莫名其妙的出现一些红叉,以下是一些个人经验:

a) 尝试先到Dos命令行窗口,用mvn clean compile(或install)之类的命令试下能否正常编译

b) 如果a) 步骤能正常编译,在回到eclipse中,项目右击->Maven-Update Project ,通常这样就能消除红叉

c) 有时候b)步骤操作完以后,仍然会有红色感叹号或红叉,但是eclipse编译、调试都OK,这就要具体问题具体分析了,可以尝试把Problems面板调出来,逐个分析

d) After the above 3 steps are invalid, you can finally try Windows -> Preferences -> Validation -> Disable All to turn off all validations

 

Reference: http://www.cnblogs.com/yjmyzz/p/3495762.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326298031&siteId=291194637