Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude a dependency from parent's project in Maven?

Tags:

java

maven

For example, I have 2 Maven projects. One is "project-parent". The other is "project-child". Obviously, "project-child" is the sub project of "project-parent".

"project-parent" has a dependency of log4j. But I want to exclude it from the "project-child". Is there a way?

You might say I should move log4j from "project-parent" to "project-child". That is totally correct. But the assumption is I CANNOT modify "project-parent"'s POM.

Thanks in advance.

like image 956
Smartmarkey Avatar asked Oct 26 '11 03:10

Smartmarkey


2 Answers

I think in Maven2 there is no way to achieve this, because this is what POM inheritance is for . However there is one trick that I can think of:

Assume you have the right to upload artifact to your internal artifact repository. You may create an empty JAR, deploy it as log4j:log4j, with a obviously abnormal version (e.g. log4j:log4j:9999 ). Add such dependency in your project-child. Then it will override the dependency of parent to depends on a in-fact-empty JAR.

like image 165
Adrian Shum Avatar answered Sep 18 '22 16:09

Adrian Shum


I don't know of a way of actually excluding a dependency, but you can exclude it from the target distribution, but it's a bit of a hack. You need to change the scope of the dependency to something that you can exclude in the final distribution.

So, say that my parent had a dependency on junit 4.8, in my pom you say:

<dependency>     <groupId>junit</groupId>     <artifactId>junit</artifactId>     <version>4.8</version>     <scope>provided</scope> </dependency> 

So we're changing the scope to provided. For an explanation of how this works, see my answer to NoClassDefFoundError: org/junit/AfterClass during annotation processing. Unfortunately, this doesn't affect the build, but when you're copying the dependencies for the final distribution, you can use the excludeScope configuration element to not copy the dependency into the final distribution:

<plugin> <artifactId>maven-dependency-plugin</artifactId>  <executions>     <execution>         <id>copy-libs</id>         <phase>package</phase>         <goals>             <goal>copy-dependencies</goal>         </goals>         <configuration>             <outputDirectory>${project.build.directory}/lib</outputDirectory>             <excludeScope>provided</excludeScope>         </configuration>     </execution> 
like image 35
Matthew Farwell Avatar answered Sep 19 '22 16:09

Matthew Farwell