Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Maven dependency with command line

I've just installed Maven 3 - I'm new to Java and I want to learn how Maven works. For now, I know that I can add a dependency by editing POM file in the maven project, but I wonder if there is a 'clean' way to do it with command line. Running Windows 8.1, Java 8, Maven 3.

like image 374
Lurker Avatar asked Mar 21 '17 15:03

Lurker


People also ask

How do I add a dependency in Maven?

Add a Java Maven Dependency to the Utility ProjectRight-click the utility project, and select Maven>Add Dependency. Type a dependency name in the Enter groupID… field (e.g., commons-logging) to search for a dependency. Select the dependency, and click OK.

How do I run a Maven dependency tree in cmd?

How to get the Maven Dependency Tree of a Project. We can run mvn dependency:tree command in the terminal to print the project dependency tree. For our example, I will be using the Mockito Tutorial project. You can download the project from the GitHub repository.


2 Answers

I'm not very sure if there's a built-in maven feature or plugin to do so, but I don't think so. You could achieve it by a small script using sed or something similar. I've used the following in a bash script:

get_foo_dep() {
  cat <<EOF
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>foo</artifactId>
        <version>${DEP_VERSION}</version>
    </dependency>
EOF
}

DEP_VERSION="1.0.0"  # just example, you can set it from somewhere
POM_FILE="pom.xml"   # just example, the path to pom

foo_dep=$(get_foo_dep)
foo_dep=${foo_dep//$'\n'/\\$'\n'}   # escape \n with \\n for sed to work
sed -i "s|<dependencies>|<dependencies>\n${foo_dep}|" "$POM_FILE"  # CARE!! it makes in-place substitution

You can also have a look at this other question, where awk is recommended:

Is it possible to use sed to replace dependencies's version in a pom file?

like image 67
Gerard Bosch Avatar answered Oct 04 '22 03:10

Gerard Bosch


Using the POM directly is probably a better way, but yes you can do that:

mvn install:install-file -Dfile=<path-to-file> -DgroupId="group-id" \
-DartifactId="artifact-id" -Dversion="version" -Dpackaging="packaging"

https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html

like image 25
achAmháin Avatar answered Oct 04 '22 02:10

achAmháin