@Component public class MyBean { private static final Logger log = LoggerFactory.getLogger("application"); ... }
@Component public class MyBean { @Autowired private Logger log; ... }
@EnableAutoConfiguration @ComponentScan public class ApplicationConfiguration { @Bean public Logger logger(){ return LoggerFactory.getLogger("application"); } ... }
@EnableAutoConfiguration @ComponentScan public class ApplicationConfiguration { @Bean @Primary public Logger logger(){ return LoggerFactory.getLogger("application"); } @Bean(name = "loggerBean") public Logger loggerBean(){ return LoggerFactory.getLogger("loggerBean"); } ... }
@Component public class MyBean { @Autowired private Logger log; @Autowired @Qualifier("loggerBean") private Logger log2; ... }
@Component public class MyBean { @Logging private Logger log; @Logging("loggerBean") private Logger log2; ... }
@Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Logging { String value(); }
public class LoggingAnnotationProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { Class clazz = bean.getClass(); do { for (Field field : clazz.getDeclaredFields()) { Logging annotation = field.getAnnotation(Logging.class); if (annotation!= null) { boolean accessible = field.isAccessible(); field.setAccessible(true); try { if(!annotation.value().isEmpty()){ field.set(bean, LoggerFactory.getLogger(annotation.value())); } else { field.set(bean, LoggerFactory.getLogger(clazz)); } } catch (IllegalAccessException e) { LoggerFactory.getLogger(this.getClass()).error(e.getMessage(), e); } field.setAccessible(accessible); } } clazz = clazz.getSuperclass(); } while (clazz != null); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) { return bean; } }
@EnableAutoConfiguration @ComponentScan public class ApplicationConfiguration { @Bean public LoggingAnnotationProcessor loggingAnnotationProcessor(){ return new LoggingAnnotationProcessor(); } ... }
Source: https://habr.com/ru/post/276729/
All Articles