2

我正在尝试通过扩展 JDBC appender 来添加自定义 appender 以将我的日志数据存储到数据库中。但是我需要从 spring 注入的 dataSource 覆盖数据库连接。它对我不起作用,因为首先加载 log4j 上下文并且 spring 上下文尚未初始化。所以我得到了 Spring 注入数据源的空指针异常。

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

**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>

我的 log4j 配置

<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>

这就是我的自定义 Appender 的样子:

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(); } } `
4

0 回答 0