Scenario:
Log Wrapper: slf4j. Each class must pass
[Java]
Private static final Logger LOGGER = LoggerFactory. getLogger (ErrorHandler. class );
Private static final Logger LOGGER = LoggerFactory. getLogger (ErrorHandler. class); this non-intelligent hard coding method is used to generate a logger instance.
Optimization:
In the spring framework, each class is instantiated by spring ioc. The BeanPostProcessor interface can implement custom logic after the instance Initialization is complete.
Spring's Annotation-based initialization class implements the BeanPostProcessor interface. For example, @ Required & RequiredAnnotationBeanPostProcessor.
The following method is used to automate the initial Logger instance-Based on spring 2.5-3.x:
1. Define Annotation:
[Java]
/**
* Log Annotation for Logger Injection
**/
@ Retention (RetentionPolicy. RUNTIME)
@ Target (ElementType. FIELD)
@ Brief ented
Public @ interface Log {
String value () default "";
}
/**
* Log Annotation for Logger Injection
**/
@ Retention (RetentionPolicy. RUNTIME)
@ Target (ElementType. FIELD)
@ Brief ented
Public @ interface Log {
String value () default "";
}
2. Define the target class:
[Java]
@ Component
Public class LoggerDemo {
@ Log
Private Logger logger;
// Some methods
// Some properties
}
@ Component
Public class LoggerDemo {
@ Log
Private Logger logger;
// Some methods
// Some properties
}
3. Custom BeanPostProcessor
[Java]
/**
* Init the slf4j logger in each spring bean
*/
@ Component
Public class LoggerBeanPostProcessor implements BeanPostProcessor {
@ Override
Public Object postProcessBeforeInitialization (final Object bean, String beanName) throws BeansException {
ReflectionUtils. doWithFields (bean. getClass (), new FieldCallback () {// spring reflection utils
@ Override
Public void doWith (Field field) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils. makeAccessible (field );
If (field. getType (). equals (Logger. class) & field. isAnnotationPresent (Log. class) {// Log Annotation check
Log logAnnotation = field. getAnnotation (Log. class );
String loggerName = logAnnotation. value ();
Logger logger = null;
If (loggerName! = Null &&! LoggerName. equals ("")){
Logger = LoggerFactory. getLogger (loggerName );
} Else {
Logger = LoggerFactory. getLogger (bean. getClass ());
}
Field. set (bean, logger); // init value
}
}
});
Return bean;
}
@ Override
Public Object postProcessAfterInitialization (Object bean, String beanName) throws BeansException {
Return bean;
}
}
<P> </P>