---
title: "使用Listener实现SessionFactory和DaoFactory的初始化"
author: "afeitech"
date: "2008-03-25T14:49:51Z"
tags: []
slug: "listener-sessionfactory-daofactory"
draft: false
lastmod: "2008-03-25T14:49:51Z"
id: 175842
url: "https://afeitech.iteye.com/blog/175842"
---

前面已经介绍了

[采用单态模式保证Hibernate的SessionFactory的单态](../../blog/175836)

和

[用DAO工厂创建并管理dao实例](../../blog/175823)

 

那么现在，我们用Listener实现在系统启动时，即完成SessionFactory实例的初始化，以及DaoFactory的初始化。

```
public class FactoryLoaderListener implements ServletContextListener {

	DaoFactory df=null;
	SessionFactory sf=null;
	
	//在系统启动时候加载
	public void contextInitialized(ServletContextEvent sce) {
		
		try{//初始化Hibernate的SessionFactory
			sf=SessionFactoryBuilder.instance().getSessionFactory();
			System.out.println("Hibernate的SessionFactory已经初始化..."+sf);
		}catch(Exception e){
			System.out.println("Hibernate的SessionFactory初始化失败..."+e);
		}
		
		try{//获取系统的DAO配置文件路径
			String path=sce.getServletContext().getRealPath("/WEB-INF/");
			df=DaoFactory.instance(path);//创建DAO工厂的实例
			System.out.println("DAO工厂已经被初始化..."+df);
		}catch(Exception e){
			System.out.println("DAO工厂初始化失败，出现异常..."+e);
		}

	}
	public void contextDestroyed(ServletContextEvent arg0) {
		 sf=null;
		 df=null;
	}
}
```

需要在web.xml增加配置

```
	<listener>
		<listener-class>
			com.afei.web.FactoryLoaderListener
		</listener-class>
	</listener>
```