使用OpenSessionInViewFilter 发生异常: No bean named 'sessionFactory'

来源:互联网 发布:好玩的网络赛车游戏 编辑:程序博客网 时间:2024/04/29 06:57

在项目中配置了OpenSessionInViewFilter

<filter><filter-name>OpenSessionInView</filter-name><filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class></filter><filter-mapping><filter-name>OpenSessionInView</filter-name><url-pattern>*.action</url-pattern></filter-mapping>

但是在访问系统的时候抛出了这个异常:org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sessionFactory' is defined。原因是OpenSessionInViewFilter这个类中有个属性叫 sessionFactoryBeanName默认值为sessionFactory,而我的配置文件中SessionFactory不叫这个名字,修改名字后正常。

API有如下解释:

Looks up the SessionFactory in Spring's root web application context. Supports a "sessionFactoryBeanName" filter init-param in web.xml ; the default bean name is "sessionFactory". Looks up the SessionFactory on each request, to avoid initialization order issues (when using ContextLoaderServlet, the root application context will get initialized after this filter).

所以,在web.xml中配置OpenSessionInViewFilter时应该指定SessionFactory的名字,配置如下:

<filter><filter-name>OpenSessionInView</filter-name><filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class><init-param><param-name>sessionFactoryBeanName</param-name><param-value>MySessionFactory</param-value></init-param></filter><filter-mapping><filter-name>OpenSessionInView</filter-name><url-pattern>*.action</url-pattern></filter-mapping>