使用java注解注入logger依赖 [英] Using java annotation to inject logger dependency

查看:152
本文介绍了使用java注解注入logger依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有 aspect-j 注释支持的 spring 以允许 @Loggable 注释.这允许根据配置自动记录一个类.

I am using spring with aspect-j annotation support to allow for an @Loggable annotation. This allows automatic logging on a class based on the configuration.

我想知道是否可以以某种方式使用此注释将 slf4j Logger 变量公开到类中以供直接使用,这样我就不必对以下效果做任何事情:

I am wondering if I can somehow use this annotation to expose an slf4j Logger variable into the class for direct use, so that I don't have to do something to the effect of:

Logger logger = LoggerFactory.getLogger(MyClass.class);

如果上述内容由于注释而隐式可用,我就可以在没有声明的情况下执行 logger.debug("..."); ,那就太好了.我不确定这是否可能.

It would be nice if the above was implicitly available due to the annotation and I could just go about doing logger.debug("..."); without the declaration. I'm not sure if this is even possible.

推荐答案

您可以使用 BeanPostProcessor 接口,该接口由 ApplicationContext 为所有创建的 bean 调用,因此您有机会填写相应的属性.

You can use the BeanPostProcessor interface, which is called by the ApplicationContext for all created beans, so you have the chance to fill the appropriate properties.

我创建了一个简单的实现,它做到了:

I created a simple implementation, which does that:

import java.lang.reflect.Field;
import java.util.List;

import net.vidageek.mirror.dsl.Mirror;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class LoggerPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        List<Field> fields = new Mirror().on(bean.getClass()).reflectAll().fields(); 
        for (Field field : fields) {
            if (Logger.class.isAssignableFrom(field.getType()) && new Mirror().on(field).reflect().annotation(InjectLogger.class) != null) {
                new Mirror().on(bean).set().field(field).withValue(LoggerFactory.getLogger(bean.getClass()));
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

您无需执行任何复杂的注册步骤,因为 ApplicationContext 能够识别 BeanPostProcessor 实例并自动注册它们.

You don't have to do any complex registration step, since the ApplicationContext is capable of recognizing BeanPostProcessor instances and automatically register them.

@InjectLogger 注释是:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface InjectLogger {
}

然后就可以轻松使用注解了:

And then you can easily use the annotation:

public static @InjectLogger Logger LOGGER;

...

LOGGER.info("Testing message");

我使用 Mirror 库来查找带注释的字段,但显然您可以执行手动查找以避免这种额外的依赖.

I used the Mirror library to find the annotated fields, but obviously you may perform a manual lookup in order to avoid this additional dependency.

避免重复代码实际上是一个好主意,甚至避免从其他类复制和粘贴 Logger 定义而产生的小问题,例如当我们忘记更改 class 参数,导致错误日志.

It's actually a nice idea to avoid repeated code, and even small issues that come from copying and paste the Logger definitions from other classes, like when we forget to change the class parameter, which leads to wrong logs.

这篇关于使用java注解注入logger依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆