2011-05-17 169 views
6

我们使用Spring获取我们所有的JDBC连接以及部分持久性框架。然而,为了编写我们自己的自定义数据库appender(它必须是一个自定义的,因为我们不允许使用由于表名称标准的默认DBAppender)。我如何从自定义Appender内部获得对spring bean/use autowire的引用?我宁愿留在春天,而不是使用普通的JDBC。从自定义logback appender使用Spring?

自定义追加程序:

import ch.qos.logback.classic.spi.ILoggingEvent; 
import ch.qos.logback.core.AppenderBase; 

public class CustomDBAppender extends AppenderBase<ILoggingEvent> { 

    protected void append(ILoggingEvent event) { 

    } 

} 

回答

1

我这样做的方式是使用AutowiredAnnotationBeanPostProcessor。

在你的appender的构造函数中,你要求AutowiredAnnotationBeanPostProcessor注入“this”。

我的意见在this article末尾详述了这项技术。本文讨论了一种类似的自动装配Hibernate实体的方法。

3

下面是我如何解决问题 - 我通过JNDI在appender的start方法中获得DataSource,然后创建我的JDBCTemplate。这对我来说非常棒 - 没有任何麻烦。

public class MyAppender extends AppenderBase<ILoggingEvent> 
{ 
    private String _jndiLocation; 
    private JDBCTemplate _jt; 

    public void setJndiLocation(String jndiLocation) 
    { 
    _jndiLocation = jndiLocation; 
    } 

    @Override 
    public void start() 
    { 
    super.start(); 

    if (_jndiLocation == null) 
    { 
     throw new IllegalStateException("Must have the JNDI location"); 
    } 
    DataSource ds; 
    Context ctx; 
    try 
    { 
     ctx = new InitialContext(); 
     Object obj = ctx.lookup(_jndiLocation); 
     ds= (DataSource) obj; 

     if (ds == null) 
     { 
     throw new IllegalStateException("Failed to obtain data source"); 
     } 
     _jt = new JDBCTemplate(ds); 
    } 
    catch (Exception ex) 
    { 
     throw new IllegalStateException("Unable to obtain data source", ex); 
    } 

    } 

    @Override 
    protected void append(ILoggingEvent e) 
    { 
    // log to database here using my JDBCTemplate instance 
    } 
} 

我不知道你是否会遇到同样的问题,但我不得不使用多步配置(described here),因为我得到SLF4J的“substitue记录器”错误消息(described here)。