大多数Java项目的依赖项清单都很长,java7developer也不例外。Maven可以帮你管理这些依赖项,它在Maven Central Repository中存了数量庞大的第三方类库。重要的是,这些第三方类库都有它们自己的pom.xml文件,其中又声明了它们各自的依赖项,Maven由此可以推断出你还需要哪些类库并下载它们。
最初会用到两个主要作用域是compile
和test
2。这跟把JAR文件放到CLASSPATH
中编译代码然后运行测试效果是完全一样的。
2 J2EE/JEE项目中通常还会有些声明为runtime
作用域的依赖项。
代码清单E-2为java7developer项目pom文件中的<dependencies>
部分。
代码清单E-2 POM:依赖项
<dependencies>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId> //❶工件的唯一ID
<version>3.0</version>
<scope>compile</scope> //❷compile作用域
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.8.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>4.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope> //❸test作用域
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.9.0</artifactId>
<version>1.6.1</version>
<scope>compile</scope> //❹compile作用域
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
<scope>test</scope>
</dependency>
</dependencies>
为了让Maven找到我们引用的工件,需要给出正确的<groupId>
、<artifactId>
和<version>
❶ 。我们在前面说过了,将<scope>
设为compile
❷会将那些JAR文件加到编译代码所用的CLASSPATH
中。
将<scope>
设为test
❸会确保Maven编译和运行测试时将这些JAR文件加到CLASSPATH
中。scalatest类库是其中比较奇怪的,它应该放在test
作用域中,但要放在compile
作用域❹ 才能用。3
3 希望这个插件的后续版本能解决这个问题。
Maven pom.xml文件并不像我们所期望的那么紧凑,但我们执行的是三种语言的构建(Java、Groovy和Scala),还能生成报告。希望随着对这一领域的工具支持不断改善,Maven构建脚本能变得更精简。