Package-only dependencies in Maven
Tom Wetjens
Sometimes you have a Maven project that needs dependencies for running tests that you do not want ending up in the final packaged WAR.
We all know the test directive in the POM that accomplishes this. You might also have dependencies that are only required at runtime and
need to be in the WAR but not on the compile classpath. Normally you would use the runtime directive in the POM. Consider a situation
where we have a dependency that we want to be available at runtime (in the WAR), but not on the classpath during the execution of our tests.
A nice example of this is logging implementations: we want to use the slf4j-simple implementation for running unit tests, but we want logback-classic
to be packaged in the WAR.
To accomplish this, you can use the maven-dependency-plugin as illustrated in the following POM snippet:
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>package-only-deps</id>
<goal>copy</goal>
<configuration>
<artifactItems>
<artifactItem>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<outputDirection>${project.build.directory}/${project.build.finalName}/WEB-INF/lib</outputDirection>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
This way you have a single logging implementation on the classpath when running tests (slf4j-simple) and a single logging implementation
for runtime in the final packaged WAR (logback-classic).