Spring框架(十二):基于纯注解的spring aop事务控制

1、创建maven项目并导入jar包的坐标

2、在domain包下创建账户实体类Account

package com.wedu.spring12.domain;

import java.io.Serializable;

/**
 * 账户实体
 */
public class Account implements Serializable{

    private Integer id;
    private Integer uid;
    private Double money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                '}';
    }
}

3、在dao包下创建持久层接口IAccountDao并添加CRUD方法

package com.wedu.spring12.dao;

import com.wedu.spring12.domain.Account;

import java.util.List;

/**
 * 账户持久层接口
 */
public interface IAccountDao {

    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 添加账户
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 修改账户
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findAccountById(Integer id);

    /**
     * 删除账户
     * @param id
     */
    void deleteAccount(Integer id);
}

4、在dao包下创建持久层接口的实现类AccountDaoImpl,实现CRUD方法并交给spring管理

package com.wedu.spring12.dao.impl;

import com.wedu.spring12.dao.IAccountDao;
import com.wedu.spring12.domain.Account;
import com.wedu.spring12.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * 账户持久层接口实现
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private QueryRunner runner;

    @Autowired
    private ConnectionUtils connectionUtils;

    @Override
    public List<Account> findAllAccount() {
        try {
            return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            runner.update(connectionUtils.getThreadConnection(),"insert into account value(?,?,?)",account.getId(),account.getUid(),account.getMoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try {
            runner.update(connectionUtils.getThreadConnection(),"update account set money=? where id=?",account.getMoney(),account.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer id) {
        try {
            return runner.query(connectionUtils.getThreadConnection(),"select * from account where id=?", new BeanHandler<Account>(Account.class), id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer id) {
        try {
            runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

5、在service包下创建业务层接口IAccountService并添加CRUD方法

package com.wedu.spring12.service;

import com.wedu.spring12.domain.Account;

import java.util.List;

/**
 * 账户业务层接口
 */
public interface IAccountService {

    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 添加账户
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 修改账户
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findAccountById(Integer id);

    /**
     * 删除账户
     * @param id
     */
    void deleteAccount(Integer id);

    /**
     * 转账业务
     * @param sourceId 转出账户
     * @param targetId 转入账户
     * @param money 转账金额
     */
    void transfer(Integer sourceId, Integer targetId, Double money);
}

6、在service包下创建业务层接口的实现类AccountServiceImpl,实现CRUD方法并交给spring管理

package com.wedu.spring12.service.impl;

import com.wedu.spring12.dao.IAccountDao;
import com.wedu.spring12.domain.Account;
import com.wedu.spring12.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 账户业务层接口实现
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public Account findAccountById(Integer id) {
        return accountDao.findAccountById(id);
    }

    @Override
    public void deleteAccount(Integer id) {
        accountDao.deleteAccount(id);
    }

    @Override
    public void transfer(Integer sourceId, Integer targetId, Double money) {
        //1、根据id查询转出账户
        Account source = accountDao.findAccountById(sourceId);
        //2、根据id查询转入账户
        Account target = accountDao.findAccountById(targetId);
        //3、设置转出金额
        source.setMoney(source.getMoney() - money);
        //4、设置转入金额
        target.setMoney(target.getMoney() + money);
        //5、更新转出账户
        accountDao.updateAccount(source);

        //int i = 1/0;

        //6、更新转入账户
        accountDao.updateAccount(target);
    }
}

7、在utils包下创建数据库连接工具类ConnectionUtils并交给spring管理

package com.wedu.spring12.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * 数据库连接工具类
 */
@Component("connectionUtils")
public class ConnectionUtils {

    @Autowired
    private DataSource dataSource;

    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /**
     * 获取当前线程上的连接
     * @return
     */
    public Connection getThreadConnection() {
        try{
            //1.先从ThreadLocal上获取
            Connection conn = threadLocal.get();
            //2.判断当前线程上是否有连接
            if (conn == null) {
                //3.从数据源中获取一个连接,并且存入ThreadLocal中
                conn = dataSource.getConnection();
                threadLocal.set(conn);
            }
            //4.返回当前线程上的连接
            return conn;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 把连接和线程解绑
     */
    public void removeConnection(){
        threadLocal.remove();
    }
}

8、在utils包下创建事务管理工具类TransactionManager,将其交给spring管理并添加spring AOP的相关注解

package com.wedu.spring12.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * 事务管理工具类
 */
@Component("txManager")
@Aspect
public class TransactionManager {

    @Autowired
    private ConnectionUtils connectionUtils;

    @Pointcut("execution(* com.wedu.spring11.service.impl.*.*(..))")
    private void pt1(){}

    /**
     * 开启事务
     */
    public void beginTransaction() {
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit() {
        try {
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public  void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 释放连接
     */
    public void release() {
        try {
            connectionUtils.getThreadConnection().close();//还回连接池中
            connectionUtils.removeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Around("pt1()")
    public Object aroundAdvice(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try {
            //1.获取参数
            Object[] args = pjp.getArgs();
            //2.开启事务
            this.beginTransaction();
            //3.执行方法
            rtValue = pjp.proceed(args);
            //4.提交事务
            this.commit();

            //返回结果
            return  rtValue;

        }catch (Throwable e){
            //5.回滚事务
            this.rollback();
            throw new RuntimeException(e);
        }finally {
            //6.释放资源
            this.release();
        }
    }
}

9、在config包下创建配置类SpringConfiguration

package com.wedu.spring12.config;

import org.springframework.context.annotation.*;

/**
 * spring配置类
 */
//指定当前类是一个配置类
@Configuration
//指定spring在创建容器时要扫描的包
@ComponentScan("com.wedu.spring12")
//导入其他配置类
@Import(JdbcConfiguration.class)
//指定properties文件的位置
@PropertySource("classpath:jdbc.properties")
@EnableAspectJAutoProxy
public class SpringConfiguration {

}

10、在config包下创建spring连接数据库的配置类JdbcConfiguration

package com.wedu.spring12.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * spring连接数据库的配置类
 */
public class JdbcConfiguration {

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Bean(name="runner")//把当前方法的返回值作为bean对象存入spring的ioc容器中
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    @Bean(name="dataSource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass(driver);
            dataSource.setJdbcUrl(url);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }
}

11、在resources下创建数据库连接文件jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

12、在测试模块中创建测试类AccountServiceTest并编写转账业务测试方法

package com.wedu.spring12.service;

import com.wedu.spring12.config.SpringConfiguration;
import com.wedu.spring12.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 基于纯注解的spring的事务控制测试
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    private IAccountService accountService;

    /**
     * 查询所有账户
     */
    @Test
    public void testFindAllAccount() {
        List<Account> accounts = accountService.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    /**
     * 转账
     */
    @Test
    public void testTransfer() {
        accountService.transfer(1,2,100d);
    }
}
 
发布了134 篇原创文章 · 获赞 10 · 访问量 7349

猜你喜欢

转载自blog.csdn.net/yu1755128147/article/details/103823397