xml文件中:
手动处理事务:
设置数据源
<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/transfer"></property> <property name="user" value="root"></property> <property name="password" value="123456"></property></bean>
创建事务管理器,因为使用的是jdbc操作数据库,所以使用DataSourceTransactionManager事务管理需要事务,事务来自Connection,即来自连接池,所以要
注入数据源。
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property></bean>
创建事务模板,事务模板需要事务,事务在管理器中,所以需要注入事务管理器
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <property name="transactionManager" ref="txManager"></property></bean>接下来就是具体的实现类来注入事务模板
<!--创建service对象,并注入dao,注入事务--> <bean id="accountServiceId" class="com.luo.transfer2.dao.serviceImpl.AccountServiceImpl"> <property name="accountDao" ref="accountDaoId"></property> <property name="transactionTemplate" ref="transactionTemplate"></property> </bean>Spring半自动管理事务(使用SpringFactoryBean创建代理对象) 使用Spring的半自动方式生成代理对象,Service就是目标类,事务就是切面类
<bean id="proxyBean" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> 代理对象要实现的接口
<property name="proxyInterfaces" value="com.luo.transfer3.service.AccountService"></property>
目标类
<property name="target" ref="accountServiceId"></property>
切面类
<property name="transactionManager" ref="txManager"></property> //注入事务的一些属性
<property name="transactionAttributes"> <!--key是service中的方法名, PROPAGATION ISOLATION -EXCEPTION +EXCEPTION 发生异常时回滚 发生异常时也不回滚 --> <props> <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop> </props> </property>-------------------------------------------------------------------------------------------------全自动方式 使用Spring的aop创建代理对象
<tx:advice transaction-manager="txManager" id="aspectId"> <!--配置事务的属性--> <tx:attributes> <tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT"/> </tx:attributes></tx:advice><aop:config> <aop:advisor advice-ref="aspectId" pointcut="execution(* com.luo.transfer4.serviceImpl..*.*(..))"></aop:advisor></aop:config>
<!--创建事务管理器,因为使用的是jdbc操作数据库,所以使用DataSourceTransactionManager 事务管理需要事务,事务来自Connection,即来自连接池,所以要注入数据源--><bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property></bean>
来源:https://www.cnblogs.com/Leroyo/p/8360270.html