---
title: "listener获取spring容器中的bean"
author: "sfeve"
date: "2011-07-08T16:47:27Z"
tags: []
categories: ["Web前端"]
slug: "listener-spring-bean"
draft: false
lastmod: "2011-07-08T21:24:28Z"
id: 1119795
url: "https://sfeve.iteye.com/blog/1119795"
---

需要实现一个功能：web容器启动的时候需要加载一个listener，去把以前开启的调度重新启动起来。这个listener需要与数据库交互，但配置数据库连接和service的bean都在spring配置文件里配置，在context-param里加载。

 

 listener加载先于context-param这个知道，但是context-param配的配置文件经测试是后加载于listener的。

 

最后综合各种资料，找到一种解决办法，如下。

 

web.xml里做如下配置：

 

```
<!-- 配置文件参数-->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>

<!-- 自己的listener -->
<listener>
	<listener-class>futureemail.core.FixTimeListener</listener-class>
</listener>
```

   
FixTimeListener.java如下：

```
public class FixTimeListener implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent event) {
		System.out.println("listener run...");

		String relativePath = event.getServletContext().getInitParameter(
				"contextConfigLocation");
		String realPath = event.getServletContext().getRealPath(relativePath);
		SpringBeanFactory.init(realPath);
		futureEmailService = (FutureEmailService) SpringBeanFactory
				.getBean("futureEmailService"); //即可取到bean

		// ....下面逻辑省略
	}

	@Override
	public void contextDestroyed(ServletContextEvent e) {
		SpringBeanFactory.clear();
	}

}
```

 

SpringBeanFactory.java如下：

 

```
public class SpringBeanFactory {
	private static ApplicationContext context;

	/**
	 * 在应用程序启动时配置spring框架
	 * 
	 * @param filePath
	 */
	public static void init(String filePath) {
		if (context == null) {
			context = new FileSystemXmlApplicationContext(filePath);
		}
	}

	public static ApplicationContext getContext() {
		return context;
	}

	/**
	 * 方法用于获取bean
	 * 
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		return context.getBean(name);
	}

	/**
	 * 在应用程序关闭时，清空spring框架配置信息
	 */
	public static void clear() {
		if (context != null) {
			context = null;
		}
	}
}
```

   
就是这样。

 

PS：部署到linux后可能会有一个问题。就是context = new FileSystemXmlApplicationContext(filePath)这里，filePath与windows下不同，会被默认成相对路径。

解决方法是：在filePath前再加一个/。代码如下：

 

```
if (filePath != null && filePath.startsWith("/")) {
	filePath = "/" + filePath;
}
```