Friday, May 5, 2017

Forcing jar or class loading order in Spring

Just recently I run into an odd problem. Due to the need to optimize some  SQL select in a one library we use, we needed to put its optimized SQL higher in the classpath. That was ok, as long as the XML file containing the optimized select was in our final module. That way it ended up inside the fat jar in "BOOT-INF/classes/" folder. Unfortunately this SQL select has to be available to all our modules so we needed it to be in our common jar.
   Unfortunately the Spring boot has no rule for jar class loading inside a directory. Fortunately there is nice Spring configuration feature called "loader.path". If set, Spring will put jars or classes provided in this path higher in classpath.
   Here is an example:

loader.path=BOOT-INF/classes/ThisClassFirst.class:BOOT-INF/lib/ThisJarNext.jar

You can place loader.path configuration into loader.properties file. That's what we did. But our common jar is versioned, so it looked something like this:

loader.path=BOOT-INF/lib/our-common-stuff-1.0.1-SNAPSHOT.jar

So now we had to solve the problem of replacing the version dynamically. To do that we used maven-replacer-plugin. So now our loader.properties file looked like:

loader.path=BOOT-INF/lib/our-common-stuff-@@COMMON_VERSION@@.jar

And our pom.xml contained following code:

<plugin>
  <groupid>com.google.code.maven-replacer-plugin</groupid>
  <artifactid>maven-replacer-plugin</artifactid>
  <version>1.3.5</version>
  <executions>
    <execution>
      <id>replaceTokens</id>
      <phase>prepare-package</phase>
      <goals>
        <goal>replace</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <file>target/classes/loader.properties</file>
    <replacements>
      <replacement>
        <token>@@COMMON_VERSION@@</token>
        <value>${our-common.version}</value>
      </replacement>
    </replacements>
  </configuration>
</plugin>


And now it works perfectly. Happy coding.

The credit for replacement plugin configuration goes to:
https://crushedbeans.wordpress.com/2013/06/08/using-maver-replacer-plugin-to-replace-strings-from-a-properties-file/

No comments:

Post a Comment