我正在考虑为 slf4j 记录器使用 CDI 注入(inject),所以我创建了一个生产者。
我将其注入(inject) ApplicationScoped
可序列化的bean:
@ApplicationScoped
public final class CurrentApplicationBean implements Serializable {
@Inject
private transient Logger logger;
}
它必须是暂时的,因为
org.slf4j.Logger
是一个不扩展 Serializable
的接口(interface),但这意味着必须在反序列化后重新注入(inject)记录器。我认为 CDI 不能处理这个问题,你知道什么?
此外,提供商总是提供一个新的
Logger
实例因为它必须从 InjectionPoint
设置记录器名称,这意味着 RequestScoped
bean 有自己的记录器实例,而不是每个类记录器的静态记录器。也许日志记录不是 CDI 注入(inject)的好上下文……您有什么考虑?
最佳答案
but this means that the logger must be re-injected after deserialization.
CDI 容器代理是可序列化的。反序列化时,代理会定位/绑定(bind)到正确的注入(inject)。我不会将注入(inject)点标记为 transient ;因为这会阻止容器定位/重新绑定(bind)注入(inject)并导致 NPE。
this means that RequestScoped beans have their own logger instance instead of a static per class logger
如果您的生产者方法类似于以下内容
@RequestScoped
@Produces
public Logger produceLog(InjectionPoint injectionPoint) {
return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
LoggerFactory.getLogger() 为每个类创建一个记录器。
Maybe logging is not a good context for CDI injection... what are your considerations?
这是你的选择。
关于logging - CDI 注入(inject)和序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11211756/