How does slf4j bind to implementation? Does it really do so during compile time?

后端 未结 6 1712
轮回少年
轮回少年 2021-02-13 03:58

In the documentation for slf4j it says that the binding happens during complie time:

\"SLF4J does not rely on any special class loader machinery. In fact, each SLF4J bi

6条回答
  •  我寻月下人不归
    2021-02-13 04:25

    It was my question too and I'd like to add my answer, since found the other two answer not clear enough (though are perfectly correct).

    First, check this line in the implementation of LoggerFactory.bind() in slf4j-api (link)

    // the next line does the binding
    StaticLoggerBinder.getSingleton();
    

    There is a class called org.slf4j.impl.StaticLoggerBinder. Check its implementation on github.

    Now go ahead and download the slf4j-api.jar from the central maven repository, extract it and find StaticLoggerBinder.class file.

    Don't try! You can't. In fact the whole org.slf4j.impl has been removed from the package. Check the pom.xml of the project:

      
        org.apache.maven.plugins
        maven-antrun-plugin
        
          
            process-classes
            
             run
            
          
        
        
          
            Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder
            
          
        
      
    

    Last, check one of the SLF4j's binding packages, for example slf4j-simple. Can you find org.slf4j.impl.StaticLoggerBinder class?

    In sum, when you have slf4j-api.jar alongside one (and only one) of the binding packages in you runtime environment, you have only one org.slf4j.impl.StaticLoggerBinder class which does the binding.

提交回复
热议问题