Spring 3.2 + Hibernate 4 OpenSessionInViewFilter

我是一个spring新手尝试我的第一个应用程序。 我的hibernate在呈现视图之前关闭,并且在延迟加载属性(预期行为)方面存在问题。 我已将OpenSessionInViewFilter添加到我的web.xml并导致以下内容:

java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered? 

事先用我所拥有的默认servlet上下文配置工作正常(有人可以告诉我为什么吗?)。 所以我添加了以下内容:

   contextConfigLocation  /WEB-INF/springapp-servlet.xml    org.springframework.web.context.ContextLoaderListener  

新的错误消失了..但仍然从hibernate获得无会话exception

 org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.test.model.Store.categories, could not initialize proxy - no Session 

我在我的一个控制器中放了一个调试消息,似乎它被初始化了3次。 也许我有多个hibernate会话工厂bean的实例? 我的控制器方法被标记为@Transactional,一切正常,直到我试图让会话打开以使视图可用的惰性字段。

我的完整web.xml(添加了新的上下文,在我添加了hibernatefilter之前没有它工作正常):

    Spring   Spring Test   contextConfigLocation  /WEB-INF/springapp-servlet.xml    org.springframework.web.context.ContextLoaderListener   hibernateFilter org.springframework.orm.hibernate4.support.OpenSessionInViewFilter  sessionFactoryBeanName sessionFactory    hibernateFilter /* REQUEST FORWARD   springapp org.springframework.web.servlet.DispatcherServlet 1   springapp /   500 /error/500   404 /resources/pages/error.html   

springapp-servlet.xml中

                 hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=true                                      

我的控制器初始化两次,相同的配置由根ApplicationContext和FrameworkServlet使用。 我已经初始化了两个上下文。 我已经为名为springapp.xml的根上下文创建了一个配置,并在那里移动了我的所有中间层配置,并在springapp-servlet.xml中保留了我的Web层配置

我的web.xml现在看起来像这样,一切正常:

   contextConfigLocation  /WEB-INF/springapp.xml    org.springframework.web.context.ContextLoaderListener   hibernateFilter org.springframework.orm.hibernate4.support.OpenSessionInViewFilter  sessionFactoryBeanName sessionFactory    hibernateFilter /* REQUEST FORWARD   springapp org.springframework.web.servlet.DispatcherServlet  contextConfigLocation /WEB-INF/springapp-servlet.xml  1   springapp /  

为了解决我的问题,它只是错过了这一行

在应用程序上下文文件中。

未考虑方法上的@Transactional注释。

希望它会帮助某人