简体   繁体   中英

API to download dependencies from pom.xml

I am trying to write a java program that takes a maven pom.xml file as input and does following:

  1. Downloads all dependencies
  2. Adds jars to classpath
  3. Executes java code (loaded from the jars)

Is it possible? any sample code to achieve #1 above will be greatly appreciated

您的要求正是Maven Exec插件已经具备的功能。

If you absolutely have to do this embeded in a Java app:

The library Maven uses under the covers to do dependency resolution is called Aether. If you take a look at the documentation on the Sonatype site there's an example of how to do step 1. Part of the dependency resolution process will give you access to a list of dependencies which you can then loop over to build your classpath.

For step 3 you could use a ProcessBuilder and launch the target Java app as a subprocess of the JVM that used Aether to build the classpath.

If you can use a shell script:

You can use mvn dependency:get -Dartifact=[group]:[artifact]:[version] to download the artifacts to your local repo.

Then you can use mvn dependency:build-classpath to generate the classpath string.

Then you can simply execute java with a -cp option. You'd have to also know what main class you want is, or you could compute the name of the primary jar from the artifact and version number and pass that to -jar.

If you're able to get the pom.xml of the main project in your deployment environment:

You can just use mvn exec:java -DmainClass=com.company.package.YourMainClass . This option is by far the simplest, but it does have the downside of executing within the maven JVM and as far as I've been able to find out there's no option for forking a separate process. Also you need to have a full fledged pom to make this work which isn't always convenient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM