基于xml(项目结构清晰)
原理就是在在spring的xml配置文件中启用aop自动生成代理,进行事务的管理
1.service的实现类
2.配置文件(基本都在这里做了,流程如下)
1.首先导入命名空间tx,aop
2.配置数据源
3.配置dao(在dao中注入数据源)
4.配置service(在service中注入dao)
5.配置事务管理器(注入数据源才能得到事务)
6.配置事务详情、通知(在aop的基础上对筛选出来的切入点使用不同的事务)
7.配置aop(利用切入点表达式确定目标类的切入点,然后引入通知,确定切入点的事务详情)
<?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: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
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置数据源
c3p0的
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_tx"></property>
<property name="user" value="root"></property>
<property name="password" value="529558445"></property>
</bean>
<!--配置dao-->
<bean id="accountDao" class="com.zm.daoImpl.AccountDaoImpl">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置service-->
<bean id="accountService" class="com.zm.serviceImpl.AccountServiceImpl">
<!--注入dao-->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--然后管理器需要事务,事务又是从连接中获得的
所以要注入数据源
-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务详情
用到事务管理器
在aop筛选基础上,对ABC三个确定使用什么样的事务。例如:AC读写、B只读
-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<!--配置事务属性
tx:method:这个就是详情的具体配置
name:就是目标类的切入点(要增强的方法)
propagation:传播行为
isolation:隔离级别
还有其他例如是否只读、异常回滚、异常提交等等
-->
<tx:attributes>
<tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP
假设目标类有ABCD(4个连接点)
利用切入点表达式确定目标类中
哪些连接点(方法)最后作为切入点(被增强的方法)(ABC)
advice-ref:引入事务详情、通知,就是通知切入点使用怎样的事务
-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.zm.serviceImpl.*.*(..))"/>
</aop:config>
</beans>
3.测试类(无异常)
数据库内容改变(两个人初始化都是10000)
4.测试类(有异常)
数据库没有发生改变,事务回滚
基于注解(开发速度快)
1.配置事务管理器,将并事务管理器交予spring
2.在目标类或目标方法添加注解即可 @Transactional
3.测试类(无异常)
4.测试类(有异常)
数据库没有改变,事务回滚
开发中,常用的就是这两种方式,xml方式虽然慢点,但是项目清晰,注解开发很快,但是躲起来的时候就会乱,可能过几天就不知道自己把注解打在哪个地方了。但是注解快啊