开发者

Maven dependency questions

So I finally took the dive and installed maven2 but I've got some problems.

My code relies on some third party jars which I installed using install:install-file. I the开发者_如何转开发n listed those jars as dependencies in my pom. Maven can compile and package it all fine and dandy. But when I run my jar like so:

java -cp "target/*" com.blah.App

It doesn't work because it cannot find some classes which are needed at runtime. Those classes are in a jar which has been installed and is used for compilation.

I have listed the scope of the dependency as for that jar as "provided". I tried using "system" as well, but that doesn't work either. What am I doing wrong?

I can get it to run if I do this though:

java -cp "target/*:path/to/jar1:path/to/jar2" com.blah.App

But there must be some way to get maven to put the required jars in the target directory.


You should not be using "provided" for normal dependencies. "Provided" is used for dependencies that are assumed to be available at runtime, such as J2EE APIs for a J2EE app.

The reason your application doesn't work is that now your dependencies are located in the maven repo, and they need to be added to the classpath.

For a normal java application such as yours, you can use the maven-dependency-plugin to copy your dependencies to a directory (from the maven repository) and configure the maven-jar-plugin to add the jar files to your manifest classpath (by creating an executable jar).

Update: You might also want to search the maven central repository to see if your dependencies are already there, so you don't have to mess around with manually installing them into your local repo. There's a good chance they're already there (if they're open source).


To learn more about the way maven deals with dependencies, the Introduction to the Dependency Mechanism and the Dependency Scope section are good starting point. Here, as pointed out in another answer, using a "provided" scope for your dependencies is not appropriate. You should use the "compile" scope which is the default and used if none is specified.

Then, to run com.blah.App in the current VM with the enclosing project's dependencies as classpath, there is the maven-exec-plugin:

mvn exec:java -Dexec.mainClass="com.blah.App"

As you can see, maven can make things really easy when you use it correctly and in the maven way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜