今天在做一个项目时用到了OpenSessionInViewFilter,其作用不再复述,Google一下一大堆。项目在自己编写的java类中测试时正常,在tomcat中发布后启动时正常,但是一访问就抛出org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sessionFactory' is defined这个异常。Google很多次都没有解决,最后发现是OpenSessionInViewFilter的问题,这个类中有个属性叫sessionFactoryBeanName默认值为sessionFactory,而我在Spring中配置的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 initializedafterthis filter).
在web.xml中配置OpenSessionInViewFilter时应该指定SessionFactory的名字,配置如下:
- <filter>
- <filter-name>HibernateOpenSession</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>HibernateOpenSession</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>