Spring+SpringMvc解决事务无效问题

来源:互联网 发布:淘宝无线展现词没有了 编辑:程序博客网 时间:2024/06/11 02:09

最近做课设,发现我的service层配置的事务没有效果,首先排查就是就是application-transcation.xml 配置的事务如下:

<!-- 事务管理器 --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!-- 通知 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="save*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="delete*" propagation="REQUIRED" /><tx:method name="insert*" propagation="REQUIRED" /><tx:method name="find*" propagation="SUPPORTS" read-only="true" /><tx:method name="get*" propagation="SUPPORTS" read-only="true" /></tx:attributes></tx:advice><!-- 切面 --><aop:config><aop:pointcut id="services"expression="execution(* com.gongyexueyuan.service.*.*(..))" /><aop:advisor pointcut-ref="services" advice-ref="txAdvice" /></aop:config>
也没有错误 但是通过查阅资料发现我的Springmvc.xml扫面是这样的:<context:component-scan base-package="com.gongyexueyuan" ></context:component-scan>  原因就是因为我通过注解扫描后率先生成Bean 扫描 @Component,  @Repository, @Service, or @Controller 以及@Autowired j接着才会加载事务配置文件 这时候事务对提前生成的对象没有作用了。所以扫描service 要在事务中生成对象这时候就需要使用
<!--
base-package   这个需要注意 因为这个配置作用是指扫描@Controller 当你写的不只是controller包的时候就需要加上
use-default-filters="false"
当你写到
com.gongyexueyuan.controller 可以不写

>
<context:component-scan base-package="com.gongyexueyuan" use-default-filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan> 
<context:component-scan base-package="com.gongyexueyuan.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan>
这时候还不可以因为这只是在加载spingmvc生成有@Controller注解的类,其他还没有比如@service 以及@Repository 等这时候就需要在application-transcation.xml配置扫描包如下:
<context:component-scan base-package="com.gongyexueyuan" ><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan> 
这个配置是除了带有@Controller 失效其他有效。这时生成的对象就加上事务控制了。

到此由于扫描包引起的事务失效得到解决。失效事务原因还有,这只是其中一种,以后望大家多多分享心得.


0 0
原创粉丝点击