Wednesday, March 16, 2011

Grails - Excluding plugin dependencies from war

I started using maven to build my Grails project, and upgraded Grails to version 1.3.7. Running mvn grails:run-app with Tomcat works fine, but when I tried to generate a war file with mvn package, and deploy that to Jetty, it failed:

Exception in thread "main" java.lang.IllegalAccessError: tried to access field
org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory
at org.slf4j.LoggerFactory.<clinit>(LoggerFactory.java:60)

Googling led me to the SLF4J FAQ (http://www.slf4j.org/faq.html) which says that this is caused by slf4j-api <= 1.5.5 being incompatible with an slf4j binding > 1.5.5. My application declares slf4j-api 1.5.8 and slf4j-log4j12 1.5.8 as dependencies. Running mvn dependency:tree didn't reveal any slf4j-api <= 1.5.5, but, indeed, in WEB-INF/lib in the application's war-file there was a slf4j-api-1.5.2.jar. Where did it come from?

When running mvn package with the log level of Ivy resolver set to "info", it seems that it was pulled in by Hibernate, through its dependencies hibernate-core and hibernate-commons-annotations. Problem solved! Grails has great support for determining which of the plugin's dependencies to exclude. In the Grails Reference Documentation it says:

If a plugin is using a JAR which conflicts with another plugin, or an application dependency then you can override how a plugin resolves its dependencies inside an application using exclusions. For example:

This means that all I have to do is include the following in my BuildConfig.groovy:

runtime("org.grails.plugins:hibernate:1.3.7") {

excludes "slf4j-api"

}

No luck. slf4j-api-1.5.2.jar was still there. Googling suggested that there is a bug in Grails that prevents it from excluding transitive dependencies of plugins (GRAILS-6910). Allright. Let me exclude hibernate-core and hibernate-comons-annotations, then, and include them as dependencies with slf4j-api excluded, ie.

This is good news that it works, however; the design seems rather hacky, doesn’t it? Adding a layer of excludes? Ewww.

The correct behavior for Maven should be to build and consult a superseding dependency graph in the build, no? Like if Hibernate is asking for slf4j version 1.5.2, Maven should look for other artifacts that need slf4j, if one needs a newer one, don’t load the older one, instead maybe print out a warning and at least try to let the newest one provide the dependency for both.