SpringMVC 注解事务


<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="txManager" />

1.配置Hibernate事务管理器

2.开启注解事务支持

遇到的问题:

1. 在service类中的方法设置@Transactional注解,但事务没有起作用,即更新操作后异常,事务没有回滚。

解决:  将事务配置转移到dispatcher-servlet.xml中。错误是因为我将事务配置放在了applicationContext.xml中,所以事务失效了,因为service层托管在了dispatcher-servlet容器中。

而事务拦截却在applicationContext容器中,导致事务失效。

<listener> 
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

 知识点:

Spring会创建一个WebApplicationContext上下文,称为父上下文(父容器) ,保存在 ServletContext中,key是 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE的值。

可以使用Spring提供的工具类取出上下文对象:WebApplicationContextUtils.getWebApplicationContext(ServletContext);

DispatcherServlet是一个Servlet,可以同时配置多个,每个 DispatcherServlet有一个自己的上下文对象(WebApplicationContext),称为子上下文(子容器),子上下文可以访问 父上下文中的内容,但父上下文不能访问子上下文中的内容。 它也保存在 ServletContext中,key 是"org.springframework.web.servlet.FrameworkServlet.CONTEXT"+Servlet名称。当一 个Request对象产生时,会把这个子上下文对象(WebApplicationContext)保存在Request对象中,key是 DispatcherServlet.class.getName() + ".CONTEXT"。

可以使用工具类取出上下文对象:RequestContextUtils.getWebApplicationContext(request);

说明 :Spring 并没有限制我们,必须使用父子上下文。我们可以自己决定如何使用。

摘自:http://elf8848.iteye.com/blog/875830/

源码中上下文获取的方法注释:

1.WebApplicationContextUtils.getWebApplicationContext(ServletContext)方法注释:

 WebApplicationContext org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)

Find the root WebApplicationContext for this web application, which is typically loaded via org.springframework.web.context.ContextLoaderListener.

Will rethrow an exception that happened on root context startup, to differentiate between a failed context startup and no context at all.

2. RequestContextUtils.getWebApplicationContext(request)  方法注释

WebApplicationContext org.springframework.web.servlet.support.RequestContextUtils.getWebApplicationContext(ServletRequest request) throws IllegalStateException

Look for the WebApplicationContext associated with the DispatcherServlet that has initiated request processing.

原文地址:https://www.cnblogs.com/beenupper/p/3381700.html