一、
<!-- Start SpringMVC配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.mvc</url-pattern>
</servlet-mapping>
<!-- End SpringMVC配置 -->
如上图Spring事务配置文件还有上下文都是通过org.springframework.web.context.ContextLoaderListener加载的,而spring MVC的Controller是通过org.springframework.web.servlet.DispatcherServlet加载的 。所以包扫描配置需要分开放
<!-- applicationContext.xml:这是能过ContextLoaderListener加载的,加载时需要排除掉Controller避免二次加载,当然我这里直接指定到了service 不排除也不会受影响,因为二次加载也会影响到事务不生效。 -->
<context:component-scan base-package="cn.test.web.*.service.*">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 扫描控制器放在Spring-mvc.xml配置文件中,同上也只扫描Controller,避免同时扫描到service导致事务不生效 -->
<context:component-scan base-package="cn.transfar.web.*.controller">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
二、
检查是否增加了注解驱动的事务管理,并增加AOP自动代理功能,这里可能会需要相入cglib.2.1_3.jar包,否则会报错
<!--支持注解驱动的事务管理,指定事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!--aspectj支持自动代理实现AOP功能 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
三、
在方法上增加 @Transactional 使其方法开始事务,注意方法是public的,另外方法里面的事务别try cacth 掉,因为你处理了事务,事务就不会自动回滚,如果一定需要try catch 请捕获后throw new RuntimeException(); 出来,否则事务也不会生效。