---
title: "log4j 重写JDBCAppender时使用spring管理的bean"
author: "cy913417"
date: "2012-07-24T09:11:29Z"
tags: []
categories: ["企业架构"]
slug: "log4j-jdbcappender-spring-bean"
draft: false
lastmod: "2016-01-22T15:40:25Z"
id: 1604973
url: "https://it456.iteye.com/blog/1604973"
---

在使用log4j往数据库里写日志时 有以下两种方式可实现：

                   1. 在自己重写的MyJDBCAppender中 手动调用applicationContext.xml时 在手动获取datasource  (bean)

                  

```
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");        
	 dataSource = (DataSource) context.getBean("dataSource");
```

                 

          

            2. 在自己重写的MyJDBCAppender中通过以下方式调用bean

```
         ServletContext  sc=(ServletContext)MyServletContextListener.local.get();
          ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc);
	     dataSource = (DataSource) context.getBean("dataSource");
```

     以上方式需要获取到servletContext。通过在web.xml添加一个监听器，在监听器中获取servletContext并存至本地：

```
public class MyServletContextListener implements ServletContextListener{
	
	public static ThreadLocal local=new ThreadLocal();

	private ServletContext context=null;


	public void contextDestroyed(ServletContextEvent event) {

		this.context=null;

	}

	//初始化

	public void contextInitialized(ServletContextEvent event) {

		this.context=event.getServletContext();
		local.set(context);//放到线程池

	}

}
```

 web.xml中配置

```
<listener>
 	<listener-class>com.xxxx.www.util.MyServletContextListener</listener-class>
 </listener>
```

 

在MyJDBCAppender 中调用

```
    ServletContext  sc=(ServletContext)MyServletContextListener.local.get();
```

 

ok,第二种方式顺利拿到spring中的各种bean.