【2018年4月13号更新修改该说明】,之前我说自动扫描要精确到Controller就可以解决回滚问题,确实可以解决问题,自动装配的范围变小了,这样其他的Service层、dao层就不能自动装配了,这样肯定不合理。
原来Spring已经有相关的配置处理这个问题了,如果你项目不能回滚,肯定是把Controller层扫进去了,
在application.xml文件中自动扫描配置新增
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>就可以了
<context:component-scan base-package="com.ylzinfo"> <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器)。不扫描Controller层 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
2017年4月27号:
最近遇到一个回滚问题,百度了一天了,终于解决了;
百度上遇到很多中情况,我记录的情况主要是以下几点(1)错误类型是Exception,加rollback-for="excepation"就可以解决,使用try()catch(){}捕获异常你确没有把他重新抛出去,直接去掉try cathc就行(2)如果是使用aop不是注解管理事务,可能是<aop:pointcut id="confService" expression="execution(* com.cn.hnust.service.impl.*.*(..)) "/>写错(3)扫描的时候把controller和service层一起扫了,造成事务还没有配置你就开始装配了 。
我的错误类型是第三种。解决方式如下:
我的事务管理用的是aop我贴出代码:
<tx:advice id="TestAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception.class"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="confService" expression="execution(* com.cn.hnust.service.impl.*.*(..)) "/>
<aop:advisor advice-ref="TestAdvice" pointcut-ref="confService"></aop:advisor>
</aop:config>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
一、首先确保你这个路径是对的
<aop:pointcut id="confService" expression="execution(* com.cn.hnust.service.impl.*.*(..)) "/>
二、在applicationControlxml(spring的配置文件)
<context:component-scan base-package="com.cn.hnust.service"></context:component-scan>
确保有这个并且最重要的是base-pakepage="com.cn.hnust.service" 不要只写base-pakepag="com",要精确到你那个要回滚的事务,一般是在service中,就是精确搭配service
三、在springmvc-servlet.xml(springMVC配置文件)
<context:component-scan base-package="com.cn.hnust.controller"></context:component-scan>
同样情况base-pakeage="com.cn.hnust.controller" 不能只写base-package="com.cn.hnust" 要精确到controller
主要的原理是因为:spring先加载springMVC-servlet.xml文件,如果只写base-package="com.cn.hnust也会把hnust下的service和controller同时装配进去,然而回滚是要先要扫描controller层,然后在service层,有一个先后顺序,所以在springMVC-servlet.xml中base-package后面的值要写到com.cn.hnust.controlle层,不要只写到com.cn.hnust;否则会把com.cn.hnus下的service和controller层同时扫进去,这样就造成事务管理都没有配置,你就开始装配了。