spring事务(二)之AspectJ声明式事务

基于< tx> 和< aop>命名空间的声明式事务管理: 目前推荐的方式,其最大特点是与 Spring AOP 结合紧密,可以充分利用切点表达式的强大支持,使得管理事务更加灵活。
项目目录结构(采用springboot+maven构建项目):
在这里插入图片描述

  1. 建表sql:
DROP TABLE IF EXISTS 'account';
create table `account` (
  `username` varchar (99),
  `salary` int (11)
);
insert into `account` (`username`, `salary`) values('小王','3000');
insert into `account` (`username`, `salary`) values('小马','3000');

# 解决时区问题
SHOW VARIABLES LIKE '%time_zone%';
SET GLOBAL TIME_ZONE = '+8:00';
  1. 导包
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!--mybatis与springboot整合 -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>
		<!-- 数据库连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.12</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.8.5</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId >
			<artifactId>aspectjweaver</artifactId >
			<version> 1.8.7</version >
		</dependency>		
  1. 配置文件
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    <!-- 配置连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 注入属性值 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/springtransaction"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!-- 第一步:配置事务管理器 -->
    <bean id="dataSourceTransactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入dataSource -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 第二步:配置事务增强 -->
    <tx:advice id="txadvice" transaction-manager="dataSourceTransactionManager">
        <!-- 做事务操作 -->
        <tx:attributes>
            <!-- 设置进行事务操作的方法匹配规则 -->
            <!-- account开头的所有方法 -->
            <!--
              propagation:事务传播行为;
              isolation:事务隔离级别;
              read-only:是否只读;
              rollback-for:发生那些异常时回滚
              timeout:事务过期时间
             -->
            <tx:method name="account*" propagation="REQUIRED"
                       isolation="DEFAULT" read-only="false" rollback-for="" timeout="-1" />
        </tx:attributes>
    </tx:advice>

    <!-- 第三步:配置切面 切面即把增强用在方法的过程 -->
    <aop:config>
        <!-- 切入点 -->
        <aop:pointcut expression="execution(* com.xicheng.springtransaction.service.TransferService.*(..))"
                      id="pointcut" />
        <!-- 切面 -->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut" />
    </aop:config>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>
  1. 创建dao层、service层、controller层,注意启动类上添加xml扫描
package com.xicheng.springtransaction.mapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * @author xichengxml
 * @date 2019/2/14 16:47
 * 编程式事务管理
 */
@Repository
public class TransferDaoImpl {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 转钱方法
     */
    public void transferMoney() {
        String sql = "update account set salary=salary-? where username=?";
        jdbcTemplate.update(sql, 1000, "Bryan");
    }

    /**
     * 收钱方法
     */
    public void receiveMoney() {
        String sql = "update account set salary=salary+? where username=?";
        jdbcTemplate.update(sql, 1000, "Cathy");
    }
}

package com.xicheng.springtransaction.service;

/**
 * @author xichengxml
 * @date 2019/2/14 20:21
 */
public interface TransferService {
    void transfer() throws Exception;
}
package com.xicheng.springtransaction.service;

import com.xicheng.springtransaction.mapper.TransferDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xichengxml
 * @date 2019/2/14 16:58
 */
@Service
public class TransferServiceImpl implements TransferService {

    @Autowired
    private TransferDaoImpl transferDao;

    @Override
    public void transfer() throws Exception {
        transferDao.transferMoney();
        // 转账出现异常,回滚事务
        int i = 10 / 0;
        transferDao.receiveMoney();
    }
}
package com.xicheng.springtransaction.controller;

import com.xicheng.springtransaction.service.TransferServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xichengxml
 * @date 2019/2/14 17:11
 */
@RestController
public class TransferController {

    @Autowired
    private TransferServiceImpl transferService;

    @RequestMapping("transfer")
    public String transfer() {
        try {
            transferService.transfer();
            return "success";
        } catch (Exception e) {
            return "fail";
        }
    }
}
package com.xicheng.springtransaction;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("spring-mybatis.xml")
public class SpringtransactionApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringtransactionApplication.class, args);
	}
}
  1. 启动项目,访问http://localhost:8080/transfer
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值