我想用log4j把日志信息保存到数据库,但是我又想让log4j使用spring配置的数据库连接池,于是我重新写了一个appender类继承于JDBCAppender,然后在spring配置文件中给其注入DataSource对象,代码如下:
package com.cxl.appender;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.log4j.jdbc.JDBCAppender;
public class MyJdbcAppender extends JDBCAppender {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public MyJdbcAppender()
{
super();
}
@Override
protected Connection getConnection() {
try {
this.connection=dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return super.connection;
}
Spring配置文件如下:
com.mysql.jdbc.Driver
jdbc:mysql://127.0.0.1:3306/scutcs
root
chen
3
10
50
60
100
30
60
<bean id="myAppender" class="com.cxl.appender.MyJdbcAppender">
<property name="dataSource" ref="dataSource"/>
</bean>
问题是:
我启动tomcat的时候,不能把dataSource注入到MyJdbcAppender对象中,dataSouce总是为null报空指针异常.