How to compile Maven project from command line with all dependencies?

时间:2016-07-11 20:04:44

标签: java maven

I have a Maven project that I can normally compile and run from eclipse but when I compile it from command line it's dependencies are missing and I'm getting errors. I can compile project only after I download dependencies and add them to c:/Java/jdk/jre/lib/ext

How can I compile project and it's dependencies from console line without adding them manually to jdk? Can compiler somehow read maven dependencies?

pom.xml

<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>TCPPing</groupId>
  <artifactId>TCPPing</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
        <groupId>commons-cli</groupId>
        <artifactId>commons-cli</artifactId>
        <version>1.3.1</version>
    </dependency>
    <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>3.3</version>
    </dependency>
        <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.6</version>
    </dependency>
  </dependencies>
</project>

2 个答案:

答案 0 :(得分:14)

从具有maven支持的IDE(Eclipse,IntellIJ)运行应用程序应该非常简单。这些IDE将负责创建正确的类路径。

如果您想手动执行此操作,请尝试以下操作:

切换到包含pom.xml的目录 执行maven命令:

mvn clean install

这将编译您的项目并创建您在pom.xml文件中定义的jar。它运行maven阶段干净,每个阶段都要安装(编译,测试等)。

然后收集您用作依赖项的所有jar文件(运行项目所需):

mvn dependency:copy-dependencies

这将执行依赖项插件,该插件会将所有依赖项复制到target/dependency

然后您可以使用以下方式运行main方法:

cd target/
java -cp TCPPing-0.0.1-SNAPSHOT.jar:dependency TCPPing

-cp定义类路径(包含类的所有位置/ jar文件/文件夹)。 TCPPing是具有main方法的运行类。

注意:适用于Linux / Mac - 我认为Windows使用;

答案 1 :(得分:-1)

Javac对maven一无所知。因此它不会使用maven pom.xml。

maven的价值在于它删除了构建,测试和发布项目的手动工作。

这包括获取依赖项,并将javac与javac一起添加到javac命令的类路径中。

您可以在maven将依赖项下载到〜/ .m2 / repository后手动执行javac。但是你需要告诉javac在哪里找到罐子。这样就可以通过classpath参数完成。

如果您在使用mvn编译后尝试运行项目,则需要在放置.class文件的同一文件夹中执行此操作。因此应该是/ target / java或类似的。

相关问题