Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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>
like image 551
asdf Avatar asked Jul 11 '16 20:07

asdf


1 Answers

It should be quite straightforward to run your application from an IDE with some maven support (Eclipse, IntellIJ). These IDE's will take care about creating the correct classpath.

If you want to do this manually, try this:

change to the directory that contains the pom.xml execute the maven command:

mvn clean install

This will compile your project and create the jar you defined in the pom.xml file. It runs the maven phases clean and every phase up to install (compile, test, etc).

Then collect all jar files you use as dependencies (required to run your project):

mvn dependency:copy-dependencies

This executes the dependency plugin which will copy all dependencies into target/dependency.

You can then run your main method using:

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

-cp defines the classpath (all locations / jar files / folders that contain classes). TCPPing is the class your run that has a main method.

Note the : is for Linux / Mac - I think windows uses a ;.

like image 139
wemu Avatar answered Oct 04 '22 01:10

wemu