-
声明式事务:AOP横切
-
编程式事务:需要在源代码中,进行事务的管理
为什么需要事务?
-
可能存在数据提交不一致的问题
-
若不在Spring中配置事务,就要在代码中手动配置
-
事务在项目中十分重要,涉及到数据的一致性和完整性
步骤:
Spring配置文件中:
-
配置声明式事务
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <constructor-arg ref="dataSource" /> <!-- <property name="dataSource" ref="datasource"/>--> </bean>
-
结合AOP实现事务的织入,配置事务通知
<tx:advice id="txAdvice" transaction-manager="transactionManager"> <!--配置事务的传播特性:propagation 默认:REQUIRED--> <tx:attributes> <!--给方法配置事务--> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice>
propagation:
-
配置事务切入
<aop:config> <!--定义切入点--> <aop:pointcut id="txPointCut" expression="execution(* com.mosang.mapper.*.*(..))"/> <!--将事务导入切入点--> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config>
由于自动装配的字段导致BeanNotOfRequiredTypeException
当您的服务类实现某个接口时,默认情况下spring会接受JDK的代理,这就是收到该错误的原因,
因此无论是通过接口使用@Autowired还是启用CGLIB代理,您都可以解决该问题。
解决方法:
Spring配置文件中加入:
<tx:annotation-driven proxy-target-class="true"
transaction-manager="transactionManager" />