Search code examples
javaclassloaderslf4j

How slf4j replace org.slf4j.impl.StaticLoggerBinder placed in sfl4j-api to real StaticLoggerBinder


There are exist classes org.slf4j.impl.StaticLoggerBinder, org.slf4j.impl.StaticMarkerBinder, org.slf4j.impl.StaticMDCBinder in slf4j api. But each binding to concrete logger should contain the same classes.

For example:

http://grepcode.com/file/repo1.maven.org/maven2/org.slf4j/slf4j-api/1.6.1/org/slf4j/impl/StaticLoggerBinder.java?av=f

and its log4j implementation: http://grepcode.com/file/repo1.maven.org/maven2/org.slf4j/slf4j-log4j12/1.6.1/org/slf4j/impl/StaticLoggerBinder.java?av=f

How java classloaders substitute it? Shouldn't here be an exception?


Solution

  • If you extract the actual slf4j-api jar you'll notice that org.slf4j.impl.StaticLoggerBinder is not actually included in the jar. SFL4J api is compiled against the class at build but it isn't actually included in the artifact. If you look at the source for org.slf4j.impl.StaticLoggerBinder in the api module it has no implementation, all the public instance methods throw UnsupportedOperationException. This is ok, again because that class is excluded from the slf4j-api jar.

    The classloader behaves normally and select the first version of org.slf4j.impl.StaticLoggerBinder that is found when the class needs to be loaded. This will generally be from the first slf4j implementation jar that it listed on the classpath.

    Note: The findPossibleStaticLoggerBinderPathSet() is only used to warn that there are multiple bindings present on the classpath. It does not actually load any bindings.