log4j自定义jdbc appender,带有spring依赖注入数据源

时间:2015-01-10 17:29:01

标签: spring log4jdbc

我试图通过扩展JDBC appender来将我的日志数据存储到数据库中来添加自定义appender。但是我需要从spring注入的dataSource覆盖数据库连接。它不适合我,因为log4j上下文首先加载,而spring上下文尚未初始化。所以我得到了Spring注入DataSource的Null指针异常。

我完全是春天的新手。如果可能,请给我一个例子。

**This is how my Spring configuration looks like..**    

 <!-- DataSource -->
<bean id="dataSource" class="*******" destroy-method="close"
    p:driverClassName="XXXXX" 
    p:url="jdbc:oracle://****"
    p:username="root"
    p:password="password"/>

<!-- Hibernate session factory -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.annotation.AnnotationSessionFactoryBean"
    p:dataSource-ref="dataSource">
    <property name="packagesToScan" value="com.beans"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
        </props>
    </property>
</bean> 

<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
       <property name="sessionFactory">        <ref bean="sessionFactory" />
</property>

My log4j Configuration

<appender name="SMTT-JDBC" class="com.XXX.XXX.CustomAppender"> <errorHandler class="org.apache.log4j.varia.FallbackErrorHandler"> <appender-ref ref="FILE"/> </errorHandler> <param name="Threshold" value="INFO"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="INSERT INTO LOGS VALUES ('%x', current_timestamp ,'%C','%p','%m')" /> </layout> </appender>

This is how my Custom Appender looks like:

public class CustomJDBCAppender extends org.apache.log4j.jdbc.JDBCAppender { protected java.sql.Connection getConnection() throws java.sql.SQLException { /* I need to get Connection From Spring configuration */ } protected void closeConnection() throws java.sql.SQLException { if (connection != null && !connection.isClosed()) connection.close(); } } `

0 个答案:

没有答案