Design Patterns, Java, Maven, Uncategorized

Missing ServiceProviders after Shading


Shading is a technique used in Maven to create a single”Uber” jar by merging the contents of ¬†your app jar and all of it’s dependent jars. This makes it easier when distributing your application since there is only one big jar to deal with.

The Java Service Provider pattern is a cool way of building loosely coupled extensible applications.

When building a jar containing such implementations a text file per interface should be created listing all of it’s implementations and placed in META-INF/services. This is used by the JVM¬†when the application needs to load (using ServiceLoader class) implementations of a particular interface¬†without explicitly¬†knowing about them.

The problem is when shading multiple jars containing service providers Maven does not merge the contents of META-INF/services by default.

The solution is to use the transformer ServicesResourceTransformer to tell the Shading plugin to merge the contents of META-INF/services in every jar it shades.

This can be specified in the pom.xml as shown below.

<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers> 
...
Advertisements