java - Spring constructor injection of SLF4J logger - how to get injection target class? -
I am trying to use a spring to put an SFL 4J timber in such a square:
@Component public class example {private finals logger logger; @ Owned Public Example (Last Logger Logger) {this.logger = Logger; }}
I have found the
Public class loggingfreebenben factory factory bean & lt; Logger & gt; {@ Override public class & lt ;? & Gt; GetObjectType () {Logistar. category; } @ Override Public Boolean is Sissington () {return false; } @ Override Public Logger getObject () throws an exception {return LoggerFactory.getLogger (* * How do I get a hold of the target class here (e.g., class)?) /); }}
Is Factory Bean the Right Way? When using Picocontainers, you get the type
of the target you received. This is a little bit in the invoice. But how do you complete it in the spring?
Here is an alternative to your solution: BeanFactoryPostProcessor You can achieve your goal with implementation
Suppose you want to create a square with logging. Here it is:
package log; Import org.apache.log4j.Logger; @ Logable public class MyBean {Private logger logger; }
As you can see that there is nothing in this class and is simply designed to be a logar container for simplicity. The only notable thing is that @logogable annotation here's source code:
package log; Import java.lang.annotation.ElementType; Import java.lang.annotation.Retention; Import java.lang.annotation.RetentionPolicy; Import java.lang.annotation.Target; @Resentime (Retention Policy. RUNTIME) @Target (ElementType.Tepee) Public @Intefase LogJobil {}
This annotation is only a marker for further processing and one of the most interesting part here Is:
package log; Import org.apache.log4j.Logger; Import org.springframework.beans.BeansException; Import org.springframework.beans.factory.config.BeanFactoryPostProcessor; Import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; Import java.lang.reflect.Field; Public class LoggerBeanFactoryPostProcessor BeanFactoryPostProcessor {Public void postProcessBeanFactory throws up BeansException {string [] names = beanFactory.getBeanDefinitionNames (); For (string name: name) {object bean = beanFactor .getBean (name); If (Bean.GetClass (). Annotation Display (LogJob.Class)) {try field field = bean.getClass (). GetDeclaredField ("Logger"); Field.setAccessible (true); Field.set (Bean, LoggerGetlogger (BeanGetClass ())); } Hold (exception e) {e.printStackTrace (); }}}}}
It searches through all the beans, and if a bean is marked as @log-in , then Start your personal area with this name logger . You can go ahead and pass some parameters in the @logogable annotation. For example, this may be a name for the fields related to the logger.
I used Log4j in this example, but I think that it will work exactly the same way as slf4j
Comments
Post a Comment