当前位置: 代码迷 >> Web前端 >> listener获取spring器皿中的bean
  详细解决方案

listener获取spring器皿中的bean

热度:502   发布时间:2012-09-03 09:48:39.0
listener获取spring容器中的bean

需要实现一个功能: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;
}
?
1 楼 guoapeng 2011-07-09  
为什么不另外写一个bean
将它配置在Spring里面,
而非写成一个Linstener不可吗?
2 楼 sfeve 2011-07-11  
guoapeng 写道
为什么不另外写一个bean
将它配置在Spring里面,
而非写成一个Linstener不可吗?

呵呵,也可以吧。listener没用过,熟悉下啦
3 楼 timer_yin 2012-05-02  
以前就是因为部署到linux,读取路径问题折腾了N天,终于弄出来了,是在前面加'/' 要是早点儿看到楼主的这个文章就好了
  相关解决方案