maven(一)pom文件讲解

来源:互联网 发布:安卓玩java游戏 编辑:程序博客网 时间:2024/06/05 20:44
maven项目的核心是pom.xml,如下:
<?xml version="1.0" encoding="UTF-8"?><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.0http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.juvenxu.mvnbook</groupId><artifactId>hello-world</artifactId><version>1.0-SNAPSHOT</version></project>

project是pom的根元素,虽然不是必须的,但使用这些属性可以让第三方工具(如IDE中的XML编辑器)帮助我们快速编辑pom。

根元素下的第一个元素modelVersion指定了当前POM模型的版本,对于Maven2及Maven3来说,它只能是4.0.0.

groupId定义了项目属于哪个,这个组往往和项目所在的组织或公司存在关联。譬如在googlecode上建立一个myapp的项目,那么groupId应该是com.googlecode.myapp..

artifactId定义了当前Maven项目在组中唯一的ID,我们为这个Hello World项目定义artifactId为hello-world。

version指定了Hello World项目当前的版本——1.0-SNAPSHOT。

maven中引入JUnit如下:

<dependency>    <groupId>junit<groupId>    <artifactId>junit<artifactId>    <version>4.7</version></dependency>
这些jar包我们都可以去maven的官方地址:http://repo1.maven.org/maven2/中找到。

一般我们创建项目,根目录存放pom.xml,主项目路径都是src/main/java,非java代码(资源文件)放到java/main/resources中,测试路径都是src/test/java,后面包名可以在groupId的基础上继续添加。


之后我们可以执行maven clean test打包,但是会报错:

因为在maven clean test中还执行了clean:clean,resources:resources,compiler:compile,resources:testResources以及compiler:testCompile。

在构将compiler:testCompile的时候失败了,Maven提示我们要使用-source 5或更高版本来启动注释,就是JUnit4的@Test注解。我们只要配置该插件让其支持1.5就可以了,如下:

<build>   <plugins>      <groupId>org.apache.maven.plugins</groupId>      <artifactId>maven-compiler-plugin</artifactId>      <conofiguration>          <source>1.5</source>          <target>1.5</target>      </configuration>   </plugins></build>

r如果此时我们使用maven clean package打包的时候,打的包是无法运行main方法的(打开jar文件中的META-INF/MANIFEST.MF文件),将无法看到Main-class一行。为了生成可执行的jar文件,需要借助maven-shade-plugin,配置如下:

<plugin><groupId>org.apache.maven.plugins</groupId>  <artifactId>maven-shade-plugins</artifactId>  <version>1.2.1</version>  <executions>    <execution>      <phase>package</phase>      <goals>        <goal>shade</goal>      </goals>      <configuration>        <transformers>          <transformer implementatiion="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">            <mainClass>com.juvenxu.mvnbook.helloworld.HelloWorld</mainClass>          </transformer>        </transformers>      </configuration>    </execution>  </executions></plugin>

plugin元素在<project><build><plugins>下面。

此时我们在通过maven clean package打包,会看到jar文件中的META-INF/MANIFEST.MF文件中包含了这样一行信息:

Main-class:com.juvenxu.mvnbook.helloworld.HelloWorld

后面就可以这样执行该jar文件:java -jar hello-world.jar.

在<version>标签的后面我们还能再加一个<packaging>jar<packaging>标签,该标签定义了打包的方式,可以是jar包或者war包。


下面一节,我们将一起介绍maven的依赖特性,这个是maven的难点之一。

原创粉丝点击