如何解决使用Java注释注入记录器依赖项
| 我正在使用带有Aspect-j注释支持的spring来允许@Loggable
注释。这允许基于配置自动登录类。
我想知道是否可以使用此批注将slf4jLogger
变量公开到类中以供直接使用,这样我就不必对以下效果做任何事情:
Logger logger = LoggerFactory.getLogger(MyClass.class);
如果上面由于注释而隐式可用,那就太好了,我可以不做声明就去做logger.debug(\"...\");
。我不确定这是否可能。
解决方法
您可以使用
BeanPostProcessor
接口,所有创建的bean都由ApplicationContext
调用,因此您有机会填充适当的属性。
我创建了一个简单的实现,该实现是:
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
个实例并自动注册它们。
ѭ9注释是:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectLogger {
}
然后,您可以轻松使用注释:
public static @InjectLogger Logger LOGGER;
...
LOGGER.info(\"Testing message\");
我使用镜像库查找带注释的字段,但是显然您可以执行手动查找以避免这种额外的依赖性。
避免重复代码,甚至是复制和粘贴其他类中的Logger
定义所引起的小问题,实际上都是一个好主意,例如,当我们忘记更改class
参数时,会导致错误的日志。
, 您不能从一个方面做到这一点,但我认为龙目岛可以以一种优雅的方式为您提供帮助。请参阅@Log注释。
, 我认为@Redder的解决方案是实现此目的的好方法。但是,我不想包括Mirror库,所以我编写了一个LoggerPostProcessor实现,它使用Java反射库代替。这里是:
package com.example.spring.postProcessor;
import com.example.annotation.InjectLogger;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
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 {
private static Logger logger = LoggerFactory.getLogger(LoggerPostProcessor.class);
/* (non-Javadoc)
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object,java.lang.String)
*/
@Override
public Object postProcessBeforeInitialization(Object bean,String beanName) throws BeansException {
List<Field> fields = Arrays.asList(bean.getClass().getDeclaredFields());
for (Field field : fields) {
if (Logger.class.isAssignableFrom(field.getType()) && field.getAnnotation(InjectLogger.class) != null) {
logger.debug(\"Attempting to inject a SLF4J logger on bean: \" + bean.getClass());
if (field != null && (field.getModifiers() & Modifier.STATIC) == 0) {
field.setAccessible(true);
try {
field.set(bean,LoggerFactory.getLogger(bean.getClass()));
logger.debug(\"Successfully injected a SLF4J logger on bean: \" + bean.getClass());
} catch (IllegalArgumentException e) {
logger.warn(\"Could not inject logger for class: \" + bean.getClass(),e);
} catch (IllegalAccessException e) {
logger.warn(\"Could not inject logger for class: \" + bean.getClass(),e);
}
}
}
}
return bean;
}
/* (non-Javadoc)
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object,java.lang.String)
*/
@Override
public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException {
return bean;
}
}
, 我想对@Redder的解决方案进行一些改进。
首先-我们可以省略新注解@Log
的介绍,取而代之的是
可以将Spring的@Autowired
注释与\'required \'标志设置为
\'false \'使Spring不检查是否注入了bean
(因为我们稍后会注入)。
第二-使用Spring的ReflectionUtils
API提供所有功能
现场发现和操作所需的方法,因此我们不需要其他外部依赖项。
这里是一个示例(在Java 8中,但可以在Java 7/6 / etc中重写,也使用slf4j
facade,但可以用任何其他记录器替换):
@Component
public class LoggerPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean,String beanName) throws BeansException {
Logger logger = getLogger(bean.getClass());
doWithFields(bean.getClass(),field -> {
makeAccessible(field);
setField(field,bean,logger);
},field -> field.isAnnotationPresent(Autowired.class) && Logger.class.equals(field.getType()));
return bean;
}
...
}
...
//logger injection candidate
@Autowired(required = false)
private Logger log;
, 由于在尝试使用CDI
做相同的事情时,我得到了第一个结果(JSR 299:上下文和依赖注入),因此此链接显示了使用CDI(以及使用Spring
的替代方法)执行此操作的直接方法:
基本上,您只需要注入:
class MyClass {
@Inject private Log log;
并拥有一个这样的记录器工厂:
@Singleton
public class LoggerFactory implements Serializable {
private static final long serialVersionUID = 1L;
static final Log log = LogFactory.getLog(LoggerFactory.class);
@Produces Log createLogger(InjectionPoint injectionPoint) {
String name = injectionPoint.getMember().getDeclaringClass().getName();
log.debug(\"creating Log instance for injecting into \" + name);
return LogFactory.getLog(name);
}
}
我发现我需要在注入的log
中添加transient
,以便在会话作用域的bean中没有得到钝化作用域异常:
@Named()
@SessionScoped()
public class MyBean implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private transient Log log;
, 这是一篇博客文章,其中包含带有所有代码的完整示例:使用Spring注入记录器
, 先驱提供了一个非常简单的BeanPostProcessor,可以为您解决所有问题。您可以使用@Log注释对Spring bean的任何字段进行注释,以使Herald在该字段中注入合适的记录器。
支持的日志记录框架:
JavaTM 2平台的核心日志记录框架
Apache Commons日志记录
Java的简单日志记录外观(SLF4J)
SLF4J扩展记录器
退回
Apache Log4j
Apache Log4j 2
JBoss日志记录
Syslog4j
Graylog的Syslog4j分支
Java Fluent Logger
也可以添加其他日志记录框架。
Github仓库:https://github.com/vbauer/herald
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。