2016-05-15 212 views
0

对于Maven项目,我有以下(简称)pom.xml。我添加了com.google.collections依赖项,但是当我执行maven clean package时,我在/target/classes目录中没有看到此依赖关系的任何类。此外,当我执行JAR时,出现错误(java.lang.NoClassDefFoundError: com/google/common/collect/Iterables)。我忘了什么?Maven未安装依赖关系

<project> 
    <groupId>edu.berkeley</groupId> 
    <artifactId>java-page-rank</artifactId> 
    <build> 
    <plugins> 
     <plugin> 
     <groupId>org.apache.maven.plugins</groupId> 
     <artifactId>maven-compiler-plugin</artifactId> 
     <configuration> 
      <source>1.6</source> 
      <target>1.6</target> 
     </configuration> 
     </plugin> 
    </plugins> 
    </build> 
    <modelVersion>4.0.0</modelVersion> 
    <name>PageRank</name> 
    <packaging>jar</packaging> 
    <version>1.0</version> 
    <dependencies> 
    <dependency> <!-- Spark dependency --> 
     <groupId>org.apache.spark</groupId> 
     <artifactId>spark-core_2.10</artifactId> 
     <version>1.6.0</version> 
    </dependency> 
    <!-- http://mvnrepository.com/artifact/com.google.collections/google-collections --> 
    <dependency> 
     <groupId>com.google.collections</groupId> 
     <artifactId>google-collections</artifactId> 
     <version>1.0</version> 
    </dependency> 
    </dependencies> 
</project> 
+1

不要使用'谷歌collections':使用'guava'代替。这是一样的,删除了错误。 –

回答

2

你不会看到target/classes依赖,这些都只是用于编译,并从$HOME/.m2/repository拍摄。

如果你需要运行所产生的罐子,你将需要:

  1. 构建完整的类路径与所有依赖(您从本地Maven仓库$HOME/.m2/repository使用罐子
  2. 创建uberjar。将包含打包成一个JAR中的所有类(你可以使用Maven在组装插件或阴影插件)

例如,对于assembly plugin你需要插件添加到插件部分:

<plugin> 
    <artifactId>maven-assembly-plugin</artifactId> 
    <version>2.6</version> 
    <configuration> 
     <descriptorRefs> 
     <descriptorRef>jar-with-dependencies</descriptorRef> 
     </descriptorRefs> 
     <archive> 
     <manifest> 
      <mainClass>package.for.the.start.Main</mainClass> 
     </manifest> 
     </archive> 
    </configuration> 
    </plugin> 

后来与assembly:single执行行家,e.g:

mvn clean package assembly:single 

产生的罐子将是target/java-page-rank-1.0-SNAPSHOT-jar-with-dependencies.jar

1

使用maven-assembly-plugin,而不是maven-compiler-plugin如果你希望你的jar包含所有的依赖

<plugin> 
<groupId>org.apache.maven.plugins</groupId> 
<artifactId>maven-assembly-plugin</artifactId> 
<version>2.6</version> 
<configuration> 
    <descriptorRefs> 
     <descriptorRef>jar-with-dependencies</descriptorRef> 
    </descriptorRefs> 
    <archive> 
     <manifest> 
      <mainClass>Main</mainClass> 
     </manifest> 
    </archive> 
</configuration> 
<executions> 
    <execution> 
     <phase>package</phase> 
     <goals> 
      <goal>single</goal> 
     </goals> 
    </execution> 
</executions>