aop:config(配置事务切面)标签,配置切面需要切入点和通知(增强),所以该中包含了aop:pointcut(配置切入点)和aop:advisor(配置通知)两个子标签。
tx:advice 标签配置事务通知,这个地方的通知就是事务,需要事务管理器。所以需要将数据源导入事务管理器,再将事务管理器导入该标签。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置自动扫描的包:主要是为了把service扫描到IOC容器中-->
<context:component-scan base-package="com.atguigu.crowd.service"/>
<!--在idea中,需要导入xml文件才可以调用里面的bean-->
<import resource="spring-persist-mybatis.xml"/>
<!--配置事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--装配数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务切面-->
<aop:config>
<!--考虑到后面整合SpringSecurity,避免把UserDetailService加入事务控制,让切入点表达式定位到serviceImpl-->
<aop:pointcut id="txPointcut" expression="execution(* *..*ServiceImpl.*(..))"/>
<!--将切入点表达式和事务通知关联起来-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<!--配置事务的属性-->
<tx:attributes>
<!--查询方法:配置只读属性,让数据库知道这是一个查询操作,能够进一步优化-->
<!--注意这个地方是要给切入点的具体方法配置事务,如果切入点具体到一个方法就无需在进行配置-->
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<tx:method name="count*" read-only="true"/>
<!--增删改:配置事务传播行为,回滚异常-->
<!--propagation属性:
REQUIRED:默认值,表示当前必须工作在事务中,如果当前线程没有开启事务,则自己开启新事务,有事务就是用已有事务。
REQUIRES_NEW:不管线程上有无事务,都自己开事务运行。
rollback-for属性:配置事务方法针对什么样到异常回滚
默认:运行时异常回滚
-->
<tx:method name="save*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
<tx:method name="remove*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
<tx:method name="batch*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>
</beans>